import React, { useState, useMemo, useEffect } from 'react';
import { JobPost, Factory, User, NeedOrderPost, JobApplication, GarmentCategory, GarmentItem } from '../types';
import { 
  Plus, 
  Calendar, 
  Layers, 
  Inbox, 
  Send,
  Building2,
  FileCheck,
  ClipboardList,
  Shirt,
  Info,
  AlertTriangle,
  CheckCircle,
  Tag,
  Clock,
  Sliders,
  Sparkles,
  FileText,
  Trash2,
  Pencil,
  MessageSquare,
  Check,
  Eye,
  CheckCircle2,
  Lock
} from 'lucide-react';

interface JobsSectionProps {
  jobs: JobPost[];
  factories: Factory[];
  user: User | null;
  onPostJob: (jobData: any) => Promise<void>;
  onUpdateJob?: (id: string, jobData: any) => Promise<void>;
  onDeleteJob?: (id: string) => Promise<void>;
  onAcceptQuote?: (jobId: string, applicationId: string) => Promise<void>;
  onAcceptQuotation?: (bidId: string, orderId: string) => Promise<void>;
  onApplyJob: (jobId: string, applyData: any) => Promise<void>;
  applications?: JobApplication[];
  needOrders: NeedOrderPost[];
  myNeedOrders?: NeedOrderPost[];
  onPostNeedOrder: (postData: any) => Promise<void>;
  onUpdateNeedOrder?: (id: string, postData: any) => Promise<void>;
  onDeleteNeedOrder: (id: string) => Promise<void>;
  onRefreshWorkspace?: () => Promise<void>;
}

export default function JobsSection({ 
  jobs, 
  factories, 
  user,
  onPostJob, 
  onUpdateJob,
  onDeleteJob,
  onAcceptQuote,
  onAcceptQuotation,
  onApplyJob,
  applications = [],
  needOrders = [],
  myNeedOrders = [],
  onPostNeedOrder,
  onUpdateNeedOrder,
  onDeleteNeedOrder,
  onRefreshWorkspace
}: JobsSectionProps) {

  // Helper checks for Single-Submission Lock Constraints
  const checkUserHasApplied = (job: JobPost): boolean => {
    if (!user) return false;
    const bidInJob = job.bids?.some(b => b.userId === user.id);
    const appInList = applications.some(a => a.jobId === job.id && a.userId === user.id);
    return Boolean(bidInJob || appInList);
  };

  const checkUserHasSentProposal = (post: NeedOrderPost): boolean => {
    if (!user) return false;
    return Boolean(post.quotes?.some(q => q.userId === user.id));
  };

  const [activeSubTab, setActiveSubTab] = useState<'all-order' | 'our-order' | 'all-need-order' | 'our-need-order'>('all-order');
  const [showPostJobModal, setShowPostJobModal] = useState(false);
  const [showApplyModal, setShowApplyModal] = useState(false);
  const [selectedJob, setSelectedJob] = useState<JobPost | null>(null);
  const [viewingDetailedJob, setViewingDetailedJob] = useState<JobPost | null>(null);
  const [editingJobId, setEditingJobId] = useState<string | null>(null);
  const [viewingBidsJob, setViewingBidsJob] = useState<JobPost | null>(null);

  // Post Sourcing Order Form States
  const [styleNumber, setStyleNumber] = useState('');
  const [category, setCategory] = useState('Knit');
  const [garmentItem, setGarmentItem] = useState('T-Shirt');
  const [isCustomCategory, setIsCustomCategory] = useState(false);
  const [customCategory, setCustomCategory] = useState('');
  const [isCustomItem, setIsCustomItem] = useState(false);
  const [customItem, setCustomItem] = useState('');
  const [quantity, setQuantity] = useState('');
  const [fobBudget, setFobBudget] = useState('');
  const [smv, setSmv] = useState('');
  const [colorsCount, setColorsCount] = useState('');
  const [poCount, setPoCount] = useState('');
  const [targetDate, setTargetDate] = useState('');
  const [description, setDescription] = useState('');

  // Need Order / Capacity Post Form States
  const [needFactoryId, setNeedFactoryId] = useState('');
  const [needCategory, setNeedCategory] = useState('Knit');
  const [needGarmentItem, setNeedGarmentItem] = useState('T-Shirt');
  const [isCustomNeedCategory, setIsCustomNeedCategory] = useState(false);
  const [customNeedCategory, setCustomNeedCategory] = useState('');
  const [isCustomNeedItem, setIsCustomNeedItem] = useState(false);
  const [customNeedItem, setCustomNeedItem] = useState('');
  const [needQuantity, setNeedQuantity] = useState('');
  const [needSewingStartDate, setNeedSewingStartDate] = useState('');
  const [showPostNeedModal, setShowPostNeedModal] = useState(false);
  const [editingNeedOrderId, setEditingNeedOrderId] = useState<string | null>(null);

  // Capacity Quotes & Sourcing Proposals States
  const [showQuotesModalPost, setShowQuotesModalPost] = useState<NeedOrderPost | null>(null);
  const [showSubmitQuoteModalPost, setShowSubmitQuoteModalPost] = useState<NeedOrderPost | null>(null);
  const [quoteCategory, setQuoteCategory] = useState('Knit');
  const [quoteQuantity, setQuoteQuantity] = useState('');
  const [quoteTargetBudget, setQuoteTargetBudget] = useState('');
  const [quoteStyleName, setQuoteStyleName] = useState('');
  const [quoteSmv, setQuoteSmv] = useState('');
  const [quoteSamplePhotos, setQuoteSamplePhotos] = useState<string[]>([]);
  const [quoteSpecDescription, setQuoteSpecDescription] = useState('');
  const [quotePhotoError, setQuotePhotoError] = useState('');
  const [confirmApproveQuoteId, setConfirmApproveQuoteId] = useState<string | null>(null);
  const [reviewingProposalQuote, setReviewingProposalQuote] = useState<any | null>(null);

  // ACI Categories & Items DB Sync State
  const [dbCategories, setDbCategories] = useState<GarmentCategory[]>([]);
  const [dbItems, setDbItems] = useState<GarmentItem[]>([]);

  const fetchAciSyncData = () => {
    fetch('/api/aci/categories')
      .then(res => res.ok ? res.json() : null)
      .then(data => {
        if (data) {
          if (Array.isArray(data.categories)) setDbCategories(data.categories);
          if (Array.isArray(data.items)) setDbItems(data.items);
        }
      })
      .catch(err => console.error('Error fetching ACI categories in JobsSection:', err));
  };

  useEffect(() => {
    fetchAciSyncData();
  }, []);

  useEffect(() => {
    if (showPostJobModal || showPostNeedModal) {
      fetchAciSyncData();
    }
  }, [showPostJobModal, showPostNeedModal]);

  const availableCategoryOptions = useMemo(() => {
    const defaultCats = [
      'Knit', 'Woven', 'Sweater', 'Denim', 'Terry', 'Fleece', 'French Terry',
      'Jersey', 'Rib', 'Interlock', 'Pique', 'Jacquard', 'Polar Fleece', 'Sherpa',
      'Mesh', 'Twill', 'Oxford', 'Poplin', 'Chambray', 'Canvas', 'Linen',
      'Corduroy', 'Satin', 'Chiffon', 'Georgette', 'Crepe', 'Velvet',
      'Outerwear', 'Activewear', 'Athleisure', 'Innerwear'
    ];
    const activeDbCats = dbCategories.filter(c => c.status === 'Active').map(c => c.name);
    return Array.from(new Set([...defaultCats, ...activeDbCats]));
  }, [dbCategories]);

  const availableItemOptions = useMemo(() => {
    const defaultItems = [
      'T-Shirt', 'Polo Shirt', 'Henley', 'Tank Top', 'Shirt (Formal)', 'Casual Shirt', 'Shirt', 'Flannel Shirt',
      'Sweatshirt', 'Hoodie', 'Jacket', 'Blazer', 'Coat', 'Suit', 'Waistcoat', 'Sweater', 'Cardigan', 'Pullover',
      'Jeans', 'Chino Pant', 'Trouser', 'Cargo Pant', 'Jogger', 'Track Pant', 'Shorts', 'Boxer', 'Brief', 'Trunk',
      'Pajama', 'Night Suit', 'Swim Shorts', 'Camisole', 'Crop Top', 'Blouse', 'Tunic', 'Kurti', 'Dress', 'Maxi Dress',
      'Midi Dress', 'Mini Dress', 'Gown', 'Jumpsuit', 'Romper', 'Skirt', 'Leggings', 'Jeggings', 'Palazzo', 'Culottes',
      'Bra', 'Panty', 'Lingerie', 'Nightdress', 'Pajama Set', 'Robe', 'Maternity Wear', 'Baby Romper', 'Bodysuit',
      'Onesie', 'Frock', 'School Uniform', 'Bib', 'Sleep Suit', 'Sports T-Shirt', 'Compression Shirt', 'Compression Pant',
      'Sports Bra', 'Tracksuit', 'Training Shorts', 'Running Shorts', 'Gym Vest', 'Yoga Pant', 'Cycling Jersey',
      'Cycling Shorts', 'Swimwear', 'Coverall', 'Boiler Suit', 'Safety Vest', 'Chef Coat', 'Medical Scrub', 'Lab Coat',
      'Apron', 'Security Uniform', 'Industrial Uniform', 'Overall', 'Basic T-Shirt', 'Underwear', 'Formal Shirt',
      'Chino', 'Vest', 'Hoodie Sweater', 'Zip Sweater', 'Knit Dress', 'Thermal Top', 'Thermal Bottom', 'Sleep Shirt',
      'Lounge Wear', 'Windbreaker', 'Raincoat', 'Parka', 'Bomber Jacket', 'Puffer Jacket', 'Trench Coat', 'Overcoat',
      'Fleece Jacket', 'Softshell Jacket', 'Office Uniform', 'Hospital Uniform', 'Hotel Uniform', 'Military Uniform',
      'Airline Uniform', 'Cap', 'Hat', 'Beanie', 'Gloves', 'Socks', 'Belt', 'Scarf', 'Muffler', 'Tie', 'Bow Tie',
      'Suspenders', 'Face Mask', 'Towel', 'Bathrobe', 'Bed Sheet', 'Pillow Cover', 'Cushion Cover', 'Blanket', 'Quilt Cover'
    ];
    const activeDbItems = dbItems.filter(i => i.status === 'Active').map(i => i.name);
    return Array.from(new Set([...defaultItems, ...activeDbItems]));
  }, [dbItems]);

  const handleProposalPhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    setQuotePhotoError('');
    if (!e.target.files) return;
    const files = Array.from(e.target.files) as File[];

    if (quoteSamplePhotos.length + files.length > 4) {
      setQuotePhotoError('Strict constraint check: You can upload a maximum of 4 sample photos.');
      alert('Strict constraint check: You can upload a maximum of 4 sample photos.');
      return;
    }

    files.forEach(file => {
      const reader = new FileReader();
      reader.onload = (uploadEvent) => {
        if (uploadEvent.target?.result) {
          setQuoteSamplePhotos(prev => {
            if (prev.length >= 4) return prev;
            return [...prev, uploadEvent.target!.result as string];
          });
        }
      };
      reader.readAsDataURL(file);
    });
  };

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

  // Media states
  const [uploadedImages, setUploadedImages] = useState<string[]>([]);
  const [uploadedVideo, setUploadedVideo] = useState<string>('');
  const [mediaError, setMediaError] = useState<string>('');
  const [lightboxImage, setLightboxImage] = useState<string | null>(null);

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    setMediaError('');
    if (!e.target.files) return;
    const files = Array.from(e.target.files) as File[];

    if (uploadedImages.length + files.length > 4) {
      setMediaError('Strict Limit: Maximum 4 product images allowed.');
      return;
    }

    const validExtensions = ['jpg', 'jpeg', 'png', 'webp'];
    for (const file of files) {
      const ext = file.name.split('.').pop()?.toLowerCase();
      if (!ext || !validExtensions.includes(ext)) {
        setMediaError('Invalid Format: Only JPG, JPEG, PNG, and WEBP images are supported.');
        return;
      }

      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result && typeof event.target.result === 'string') {
          setUploadedImages(prev => {
            if (prev.length >= 4) return prev;
            return [...prev, event.target!.result as string];
          });
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleVideoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    setMediaError('');
    if (!e.target.files || e.target.files.length === 0) return;
    const file = e.target.files[0];

    const ext = file.name.split('.').pop()?.toLowerCase();
    const validExtensions = ['mp4', 'mov'];
    if (!ext || !validExtensions.includes(ext)) {
      setMediaError('Invalid Format: Only MP4 and MOV videos are supported.');
      return;
    }

    const reader = new FileReader();
    reader.onload = (event) => {
      if (event.target?.result && typeof event.target.result === 'string') {
        setUploadedVideo(event.target.result);
      }
    };
    reader.readAsDataURL(file);
  };

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

  const removeVideo = () => {
    setUploadedVideo('');
  };

  // Apply Sourcing Proposal Form States
  const [selectedFactoryId, setSelectedFactoryId] = useState('');
  const [priceBid, setPriceBid] = useState('');
  const [coverNote, setCoverNote] = useState('');

  // Filter lists based on the sub-tab
  const ourSourcingOrders = jobs.filter(j => j.userId === user?.id);
  const otherSourcingOrders = jobs.filter(j => j.userId !== user?.id);

  // Active capacity/need orders for public 'All Need Order' tab (exclude closed/approved posts)
  const displayAllNeedOrders = useMemo(() => {
    return needOrders.filter(post => {
      const isApprovedOrClosed = Boolean(
        post.isClosed || 
        post.quotes?.some(q => q.status === 'Approved')
      );
      return !isApprovedOrClosed;
    });
  }, [needOrders]);

  // Check if the current user has at least one Approved factory
  const userFactories = factories.filter(f => f.userId === user?.id);
  const approvedFactories = userFactories.filter(f => f.status === 'Approved');
  const hasApprovedFactory = approvedFactories.length > 0;

  const isRestricted = Boolean(user && user.status !== 'Approved');

  const checkRestrictedAndAlert = (): boolean => {
    if (isRestricted) {
      alert(`Account Action Restricted: Your account status is currently ${user?.status || 'Pending'}. Posting orders, submitting quotes, or executing contracts requires administrator account approval from Admin Console.`);
      return true;
    }
    return false;
  };

  const handleOpenPostJobModal = () => {
    if (checkRestrictedAndAlert()) return;
    setEditingJobId(null);
    setStyleNumber('');
    setCategory('Knit');
    setGarmentItem('T-Shirt');
    setIsCustomCategory(false);
    setCustomCategory('');
    setIsCustomItem(false);
    setCustomItem('');
    setQuantity('');
    setFobBudget('');
    setSmv('');
    setColorsCount('');
    setPoCount('');
    setTargetDate('');
    setDescription('');
    setUploadedImages([]);
    setUploadedVideo('');
    setMediaError('');
    setShowPostJobModal(true);
  };

  const handleStartEditJob = (job: JobPost) => {
    if (checkRestrictedAndAlert()) return;
    setEditingJobId(job.id);
    setStyleNumber(job.styleNumber || '');
    
    const standardCategories = ['Knit', 'Woven', 'Sweater', 'Denim', 'Outerwear', 'Activewear', 'Athleisure'];
    const jobCat = job.category || 'Knit';
    if (standardCategories.includes(jobCat)) {
      setCategory(jobCat);
      setIsCustomCategory(false);
      setCustomCategory('');
    } else {
      setCategory('Knit');
      setIsCustomCategory(true);
      setCustomCategory(jobCat);
    }

    const standardItems = ['T-Shirt', 'Jacket', 'Trouser', 'Shirt', 'Polo', 'Sweater', 'Hoodie'];
    const jobItem = job.garmentItem || 'T-Shirt';
    if (standardItems.includes(jobItem)) {
      setGarmentItem(jobItem);
      setIsCustomItem(false);
      setCustomItem('');
    } else {
      setGarmentItem('T-Shirt');
      setIsCustomItem(true);
      setCustomItem(jobItem);
    }

    setQuantity(job.quantity ? String(job.quantity) : '');
    setFobBudget(job.fobBudget ? String(job.fobBudget) : '');
    setSmv(job.smv ? String(job.smv) : '');
    setColorsCount(job.colorsCount ? String(job.colorsCount) : '');
    setPoCount(job.poCount ? String(job.poCount) : '');
    setTargetDate(job.targetDate ? job.targetDate.split('T')[0] : '');
    setDescription(job.description || '');
    setUploadedImages(job.images || []);
    setUploadedVideo(job.videoUrl || '');
    setMediaError('');
    setShowPostJobModal(true);
  };

  // Submit new/edited sourcing order
  const handlePostJobSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (checkRestrictedAndAlert()) return;
    
    const finalCategory = isCustomCategory ? customCategory.trim() : category;
    const finalGarmentItem = isCustomItem ? customItem.trim() : garmentItem;

    if (
      !styleNumber || 
      !finalCategory || 
      !finalGarmentItem || 
      !quantity || 
      !fobBudget || 
      !smv || 
      !colorsCount || 
      !poCount || 
      !targetDate || 
      !description
    ) {
      alert('Please fill out all industry-specific merchandising fields.');
      return;
    }

    const jobData = {
      styleNumber,
      category: finalCategory,
      garmentItem: finalGarmentItem,
      quantity: Number(quantity),
      fobBudget: Number(fobBudget),
      smv: Number(smv),
      colorsCount: Number(colorsCount),
      poCount: Number(poCount),
      targetDate,
      description,
      images: uploadedImages,
      videoUrl: uploadedVideo
    };

    if (editingJobId && onUpdateJob) {
      await onUpdateJob(editingJobId, jobData);
    } else {
      await onPostJob(jobData);
    }

    // Reset Form
    setEditingJobId(null);
    setStyleNumber('');
    setCategory('Knit');
    setGarmentItem('T-Shirt');
    setIsCustomCategory(false);
    setCustomCategory('');
    setIsCustomItem(false);
    setCustomItem('');
    setQuantity('');
    setFobBudget('');
    setSmv('');
    setColorsCount('');
    setPoCount('');
    setTargetDate('');
    setDescription('');
    setUploadedImages([]);
    setUploadedVideo('');
    setMediaError('');
    setShowPostJobModal(false);
  };

  // Submit contract bid
  const handleApplySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (checkRestrictedAndAlert()) return;
    if (!selectedJob) return;

    // Validation rule check
    const selectedFactory = factories.find(f => f.id === selectedFactoryId);
    if (!selectedFactory || selectedFactory.status !== 'Approved') {
      alert('Error: You can only link an Admin-Approved factory to an order bid.');
      return;
    }

    if (selectedJob && checkUserHasApplied(selectedJob)) {
      alert('Single-Bid Lock: You have already applied and submitted a quotation for this sourcing order.');
      return;
    }

    if (!selectedFactoryId || !priceBid || !coverNote) {
      alert('Please select a factory and provide pricing bid / notes.');
      return;
    }

    await onApplyJob(selectedJob.id, {
      factoryId: selectedFactoryId,
      priceBid,
      coverNote
    });

    // Reset
    setSelectedFactoryId('');
    setPriceBid('');
    setCoverNote('');
    setShowApplyModal(false);
    setSelectedJob(null);
  };

  // Submit new/edited capacity/need-order post
  const handlePostNeedOrderSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (checkRestrictedAndAlert()) return;
    
    const finalCategory = isCustomNeedCategory ? customNeedCategory : needCategory;
    const finalGarmentItem = isCustomNeedItem ? customNeedItem : needGarmentItem;

    if (!needFactoryId || !finalCategory || !finalGarmentItem || !needQuantity || !needSewingStartDate) {
      alert('Please fill out all required fields.');
      return;
    }

    const selectedFactory = factories.find(f => f.id === needFactoryId);
    if (!selectedFactory || selectedFactory.status !== 'Approved') {
      alert('Error: You can only select one of your Admin-Approved factories.');
      return;
    }

    const postData = {
      factoryId: needFactoryId,
      category: finalCategory,
      garmentItem: finalGarmentItem,
      quantity: Number(needQuantity),
      sewingStartDate: needSewingStartDate
    };

    if (editingNeedOrderId && onUpdateNeedOrder) {
      await onUpdateNeedOrder(editingNeedOrderId, postData);
    } else {
      await onPostNeedOrder(postData);
    }

    // Reset Form
    setNeedFactoryId('');
    setNeedCategory('Knit');
    setNeedGarmentItem('T-Shirt');
    setIsCustomNeedCategory(false);
    setCustomNeedCategory('');
    setIsCustomNeedItem(false);
    setCustomNeedItem('');
    setNeedQuantity('');
    setNeedSewingStartDate('');
    setEditingNeedOrderId(null);
    setShowPostNeedModal(false);
  };

  const handleOpenPostNeedModal = () => {
    setNeedFactoryId('');
    setNeedCategory('Knit');
    setNeedGarmentItem('T-Shirt');
    setIsCustomNeedCategory(false);
    setCustomNeedCategory('');
    setIsCustomNeedItem(false);
    setCustomNeedItem('');
    setNeedQuantity('');
    setNeedSewingStartDate('');
    setEditingNeedOrderId(null);
    setShowPostNeedModal(true);
  };

  const handleStartEditNeedOrder = (post: NeedOrderPost) => {
    if (post.quotes && post.quotes.length > 0) {
      alert("This need order post cannot be edited because proposals have already been submitted for it.");
      return;
    }
    setNeedFactoryId(post.factoryId);
    
    const standardCategories = ["Knit", "Woven", "Sweater", "Denim", "Outerwear", "Activewear"];
    if (post.category && !standardCategories.includes(post.category)) {
      setIsCustomNeedCategory(true);
      setCustomNeedCategory(post.category);
    } else {
      setIsCustomNeedCategory(false);
      setNeedCategory(post.category || 'Knit');
    }

    const standardItems = ["T-Shirt", "Jacket", "Trouser", "Shirt", "Polo", "Sweater", "Hoodie"];
    const gItem = post.garmentItem || '';
    if (gItem && !standardItems.includes(gItem)) {
      setIsCustomNeedItem(true);
      setCustomNeedItem(gItem);
    } else {
      setIsCustomNeedItem(false);
      setNeedGarmentItem(gItem || 'T-Shirt');
    }

    setNeedQuantity(String(post.quantity));
    const formattedDate = post.sewingStartDate ? post.sewingStartDate.split('T')[0] : '';
    setNeedSewingStartDate(formattedDate);
    setEditingNeedOrderId(post.id);
    setShowPostNeedModal(true);
  };

  const handleApproveQuote = async (postId: string, quoteId: string) => {
    // Sandbox-safe notification helpers
    const safeAlert = (msg: string) => {
      try {
        alert(msg);
      } catch (err) {
        console.warn('Native alert blocked by sandboxed iframe environment:', msg, err);
      }
    };

    try {
      const res = await fetch(`/api/need-orders/${postId}/quotes/${quoteId}/approve`, {
        method: 'PATCH'
      });
      const data = await res.json();
      if (data.success) {
        if (onRefreshWorkspace) {
          await onRefreshWorkspace();
        }
        setShowQuotesModalPost(null);
        setConfirmApproveQuoteId(null);
        safeAlert('Sourcing proposal successfully approved! This listing is now closed and secured.');
      } else {
        safeAlert(data.error || 'Failed to approve quotation.');
      }
    } catch (e) {
      console.error('Error approving proposal:', e);
      safeAlert('An unexpected error occurred while approving the proposal.');
    }
  };

  const handleSubmitQuote = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!showSubmitQuoteModalPost) return;

    if (checkUserHasSentProposal(showSubmitQuoteModalPost)) {
      alert('Single-Proposal Lock: You have already submitted an inquiry or proposal for this capacity listing.');
      return;
    }

    if (quoteSamplePhotos.length > 4) {
      alert('Strict constraint check: You can upload a maximum of 4 sample photos.');
      return;
    }

    try {
      const res = await fetch(`/api/need-orders/${showSubmitQuoteModalPost.id}/quotes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          category: showSubmitQuoteModalPost.category,
          quantity: Number(quoteQuantity),
          targetBudget: Number(quoteTargetBudget),
          styleName: quoteStyleName,
          smv: Number(quoteSmv),
          samplePhotos: quoteSamplePhotos,
          specDescription: quoteSpecDescription
        })
      });
      const data = await res.json();
      if (data.success) {
        if (onRefreshWorkspace) {
          await onRefreshWorkspace();
        }
        setShowSubmitQuoteModalPost(null);
        alert(`Sourcing proposal with complete specifications successfully sent to ${showSubmitQuoteModalPost.factoryName}! They have been notified.`);
      } else {
        alert(data.error || 'Failed to send sourcing proposal.');
      }
    } catch (e) {
      console.error('Error submitting quote:', e);
      alert('An unexpected error occurred while sending your proposal.');
    }
  };

  return (
    <div className="space-y-6">
      {/* Upper Title and Workspace Switchers */}
      <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm">
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
          <div className="space-y-1">
            <div className="flex items-center space-x-2">
              <span className="bg-blue-100 text-blue-700 px-2.5 py-0.5 rounded-full text-[10px] font-bold font-mono tracking-wider uppercase">
                Merchandising Hub
              </span>
            </div>
            <h1 className="text-2xl font-sans font-extrabold tracking-tight text-slate-900">
              Garment Sourcing & Order Board
            </h1>
            <p className="text-slate-500 text-xs">
              Manage production allocations, request quotes for sewing styles, and bid on global active contracts.
            </p>
          </div>

          {/* Sub-tab view switchers */}
          <div className="flex bg-slate-100 p-1 rounded-xl border border-slate-200 self-stretch sm:self-auto shrink-0 flex-wrap gap-1 sm:gap-0">
            <button
              onClick={() => setActiveSubTab('all-order')}
              className={`flex-1 sm:flex-initial px-5 py-2 rounded-lg text-xs font-bold transition duration-150 cursor-pointer flex items-center justify-center space-x-2 ${
                activeSubTab === 'all-order'
                  ? 'bg-white text-slate-900 shadow-sm'
                  : 'text-slate-500 hover:text-slate-900'
              }`}
            >
              <ClipboardList className="w-4 h-4" />
              <span>All Order</span>
              <span className={`text-[9px] px-1.5 py-0.2 rounded-full font-mono ${
                activeSubTab === 'all-order' ? 'bg-blue-100 text-blue-700' : 'bg-slate-200 text-slate-600'
              }`}>
                {otherSourcingOrders.length}
              </span>
            </button>
            <button
              onClick={() => setActiveSubTab('our-order')}
              className={`flex-1 sm:flex-initial px-5 py-2 rounded-lg text-xs font-bold transition duration-150 cursor-pointer flex items-center justify-center space-x-2 ${
                activeSubTab === 'our-order'
                  ? 'bg-white text-slate-900 shadow-sm'
                  : 'text-slate-500 hover:text-slate-900'
              }`}
            >
              <Shirt className="w-4 h-4" />
              <span>Our Order</span>
              <span className={`text-[9px] px-1.5 py-0.2 rounded-full font-mono ${
                activeSubTab === 'our-order' ? 'bg-blue-100 text-blue-700' : 'bg-slate-200 text-slate-600'
              }`}>
                {ourSourcingOrders.length}
              </span>
            </button>
            <button
              onClick={() => setActiveSubTab('all-need-order')}
              className={`flex-1 sm:flex-initial px-5 py-2 rounded-lg text-xs font-bold transition duration-150 cursor-pointer flex items-center justify-center space-x-2 ${
                activeSubTab === 'all-need-order'
                  ? 'bg-white text-slate-900 shadow-sm'
                  : 'text-slate-500 hover:text-slate-900'
              }`}
            >
              <Building2 className="w-4 h-4" />
              <span>All Need Order</span>
              <span className={`text-[9px] px-1.5 py-0.2 rounded-full font-mono ${
                activeSubTab === 'all-need-order' ? 'bg-blue-100 text-blue-700' : 'bg-slate-200 text-slate-600'
              }`}>
                {displayAllNeedOrders.length}
              </span>
            </button>
            <button
              onClick={() => setActiveSubTab('our-need-order')}
              className={`flex-1 sm:flex-initial px-5 py-2 rounded-lg text-xs font-bold transition duration-150 cursor-pointer flex items-center justify-center space-x-2 ${
                activeSubTab === 'our-need-order'
                  ? 'bg-white text-slate-900 shadow-sm'
                  : 'text-slate-500 hover:text-slate-900'
              }`}
            >
              <Building2 className="w-4 h-4 text-blue-500" />
              <span>Our Need Order</span>
              <span className={`text-[9px] px-1.5 py-0.2 rounded-full font-mono ${
                activeSubTab === 'our-need-order' ? 'bg-blue-100 text-blue-700' : 'bg-slate-200 text-slate-600'
              }`}>
                {myNeedOrders.length}
              </span>
            </button>
          </div>
        </div>
      </div>

      {/* Main Sourcing List Content */}
      {activeSubTab === 'all-order' && (
        <div className="space-y-6">
          {/* Header for All Orders */}
          <div className="flex justify-between items-center px-2">
            <div>
              <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400 font-mono">
                Live Sourcing Orders ({otherSourcingOrders.length})
              </h3>
              <p className="text-[11px] text-slate-500">Public market orders ready for capacity quoting.</p>
            </div>
          </div>

          {otherSourcingOrders.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-2xl p-12 text-center max-w-lg mx-auto space-y-4 shadow-sm">
              <div className="bg-slate-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-slate-400 border border-slate-100">
                <Inbox className="w-6 h-6" />
              </div>
              <div className="space-y-1">
                <p className="font-bold text-sm text-slate-800">No external orders posted</p>
                <p className="text-xs text-slate-500 max-w-xs mx-auto">There are currently no active apparel sourcing orders from other buyers available for bidding.</p>
              </div>
            </div>
          ) : (
            <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-slate-900 text-white text-[11px] font-mono uppercase tracking-wider">
                      <th className="py-3 px-4 font-bold">Order Number</th>
                      <th className="py-3 px-4 font-bold">Category / Item</th>
                      <th className="py-3 px-4 font-bold">Target Quantity / FOB</th>
                      <th className="py-3 px-4 font-bold">Accept Quantity / FOB</th>
                      <th className="py-3 px-4 font-bold text-center">Proceed</th>
                      <th className="py-3 px-4 font-bold text-center">ACTION</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 text-xs">
                    {otherSourcingOrders.map(job => {
                      const bidCount = job.bids?.length || 0;
                      const approvedBid = job.bids?.find(b => b.status === 'Approved');
                      const isAccepted = Boolean(approvedBid || (job as any).acceptedPrice || job.isClosed);
                      const isJobProceed = Boolean(job.isProceed || (job as any).proceed_status === 'In Progress');
                      const isUserApplied = checkUserHasApplied(job);
                      const isHighlighted = isAccepted || isUserApplied;
                      
                      const jobEmpCode = (job as any).assigned_employee_code || job.assigned_staff_id || (job as any).assigned_employee_id;
                      const jobEmpName = job.assigned_employee_name;
                      const jobEmpPhone = job.assigned_employee_phone || (job as any).assigned_employee_mobile;

                      const jobEmpCodeDisplay = (!jobEmpCode || jobEmpCode.startsWith('user-')) ? 'EMP-20455' : jobEmpCode;
                      const jobEmpNameDisplay = jobEmpName || 'Alex Mercer';
                      const jobEmpPhoneDisplay = jobEmpPhone || '+1234567890';
                      
                      const orderNumber = (job as any).order_number || job.id;
                      const category = job.category;
                      const garmentItem = job.garmentItem || 'N/A';
                      
                      const targetQty = `${(job.quantity || 0).toLocaleString()} Pcs`;
                      const targetFob = job.fobBudget 
                        ? `৳${job.fobBudget.toFixed(2)} / Pcs` 
                        : (job.budget || '--');
                        
                      const acceptedQty = isAccepted ? `${(job.quantity || 0).toLocaleString()} Pcs` : '--';
                      const acceptedFob = approvedBid 
                        ? `৳${Number(approvedBid.priceBid).toFixed(2)} / Pcs` 
                        : ((job as any).acceptedPrice 
                          ? `৳${Number((job as any).acceptedPrice).toFixed(2)} / Pcs` 
                          : '--');

                      return (
                        <tr key={job.id} className={`transition duration-150 ${isHighlighted ? 'bg-rose-50/80 hover:bg-rose-100/80' : 'hover:bg-slate-50/80'}`}>
                          {/* 1. Order Number */}
                          <td className="py-3.5 px-4 font-bold text-slate-900 font-mono whitespace-nowrap">
                            <div className="flex items-center space-x-2">
                              <span>{orderNumber}</span>
                              {job.isClosed ? (
                                <span className="text-[9px] bg-slate-100 text-slate-600 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Closed
                                </span>
                              ) : (
                                <span className="text-[9px] bg-emerald-50 text-emerald-700 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Active
                                </span>
                              )}
                              {isUserApplied && (
                                <span className="text-[9px] bg-rose-100 text-rose-800 border border-rose-200 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Applied
                                </span>
                              )}
                            </div>
                          </td>

                          {/* 2. Category / Item */}
                          <td className="py-3.5 px-4">
                            <div className="font-bold text-slate-900">{category}</div>
                            <div className="text-xs text-slate-500 font-medium mt-0.5">{garmentItem}</div>
                          </td>

                          {/* 3. Target Quantity / FOB */}
                          <td className="py-3.5 px-4 font-mono">
                            <div className="font-bold text-slate-900">{targetQty}</div>
                            <div className="text-xs font-bold text-emerald-700 mt-0.5">{targetFob}</div>
                          </td>

                          {/* 4. Accept Quantity / FOB */}
                          <td className="py-3.5 px-4 font-mono">
                            <div className={`font-bold ${isAccepted ? 'text-slate-900' : 'text-slate-400'}`}>
                              {acceptedQty}
                            </div>
                            <div className={`text-xs font-bold mt-0.5 ${isAccepted ? 'text-emerald-700' : 'text-slate-400'}`}>
                              {acceptedFob}
                            </div>
                          </td>

                          {/* 5. Proceed */}
                          <td className="py-3.5 px-4 text-center whitespace-nowrap">
                            {isJobProceed ? (
                              <div className="flex flex-col items-center justify-center text-center leading-tight space-y-0.5">
                                <span className="font-mono text-[11px] font-bold text-slate-800">{jobEmpCodeDisplay}</span>
                                <span className="text-[11px] font-semibold text-slate-700">{jobEmpNameDisplay}</span>
                                <span className="font-mono text-[10px] text-slate-500">{jobEmpPhoneDisplay}</span>
                              </div>
                            ) : (
                              <span className="text-[10px] bg-slate-100 text-slate-500 border border-slate-200 font-medium px-2.5 py-1 rounded-full font-mono uppercase inline-block">
                                Pending
                              </span>
                            )}
                          </td>

                          {/* 6. ACTION */}
                          <td className="py-3.5 px-4 text-center">
                            <div className="flex items-center justify-center">
                              {/* View Button */}
                              <button
                                onClick={() => setViewingDetailedJob(job)}
                                className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-3.5 py-1.5 rounded-lg transition shadow-xs flex items-center space-x-1.5 cursor-pointer"
                                title="View complete details of this sourcing request"
                              >
                                <Eye className="w-3.5 h-3.5" />
                                <span>View</span>
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {activeSubTab === 'our-order' && (
        <div className="space-y-6">
          {/* Header for Our Orders */}
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center px-2 gap-4">
            <div>
              <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400 font-mono">
                Our Sourcing Requests ({ourSourcingOrders.length})
              </h3>
              <p className="text-[11px] text-slate-500">Manage orders posted by your buyer profile.</p>
            </div>
            <button
              onClick={handleOpenPostJobModal}
              className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-4 py-2.5 rounded-xl shadow-sm transition flex items-center space-x-1.5 cursor-pointer self-stretch sm:self-auto text-center"
            >
              <Plus className="w-4 h-4" />
              <span>Post Sourcing Order</span>
            </button>
          </div>

          {ourSourcingOrders.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-2xl p-12 text-center max-w-lg mx-auto space-y-4 shadow-sm">
              <div className="bg-slate-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-slate-400 border border-slate-100">
                <Shirt className="w-6 h-6" />
              </div>
              <div className="space-y-1">
                <p className="font-bold text-sm text-slate-800">You haven't posted any orders</p>
                <p className="text-xs text-slate-500 max-w-xs mx-auto">Click "Post Sourcing Order" to submit your style specification sheet and request quotes from manufacturers.</p>
              </div>
              <button
                onClick={handleOpenPostJobModal}
                className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-4 py-2 rounded-lg shadow-sm transition cursor-pointer"
              >
                Create Sourcing Request
              </button>
            </div>
          ) : (
            <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-slate-900 text-white text-[11px] font-mono uppercase tracking-wider">
                      <th className="py-3 px-4 font-bold">Order Number</th>
                      <th className="py-3 px-4 font-bold">Category / Item</th>
                      <th className="py-3 px-4 font-bold">Target Quantity / FOB</th>
                      <th className="py-3 px-4 font-bold">Accept Quantity / FOB</th>
                      <th className="py-3 px-4 font-bold text-center">Proceed</th>
                      <th className="py-3 px-4 font-bold text-center">ACTION</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 text-xs">
                    {ourSourcingOrders.map(job => {
                      const bidCount = job.bids?.length || 0;
                      const approvedBid = job.bids?.find(b => b.status === 'Approved');
                      const isAccepted = Boolean(approvedBid || (job as any).acceptedPrice || job.isClosed);
                      const isJobProceed = Boolean(job.isProceed || (job as any).proceed_status === 'In Progress');
                      
                      const jobEmpCode = (job as any).assigned_employee_code || job.assigned_staff_id || (job as any).assigned_employee_id;
                      const jobEmpName = job.assigned_employee_name;
                      const jobEmpPhone = job.assigned_employee_phone || (job as any).assigned_employee_mobile;

                      const jobEmpCodeDisplay = (!jobEmpCode || jobEmpCode.startsWith('user-')) ? 'EMP-20455' : jobEmpCode;
                      const jobEmpNameDisplay = jobEmpName || 'Alex Mercer';
                      const jobEmpPhoneDisplay = jobEmpPhone || '+1234567890';
                      
                      const orderNumber = (job as any).order_number || job.id;
                      const category = job.category;
                      const garmentItem = job.garmentItem || 'N/A';
                      
                      const targetQty = `${(job.quantity || 0).toLocaleString()} Pcs`;
                      const targetFob = job.fobBudget 
                        ? `৳${job.fobBudget.toFixed(2)} / Pcs` 
                        : (job.budget || '--');
                        
                      const acceptedQty = isAccepted ? `${(job.quantity || 0).toLocaleString()} Pcs` : '--';
                      const acceptedFob = approvedBid 
                        ? `৳${Number(approvedBid.priceBid).toFixed(2)} / Pcs` 
                        : ((job as any).acceptedPrice 
                          ? `৳${Number((job as any).acceptedPrice).toFixed(2)} / Pcs` 
                          : '--');

                      return (
                        <tr key={job.id} className={`transition duration-150 ${isAccepted ? 'bg-rose-50/80 hover:bg-rose-100/80' : 'hover:bg-slate-50/80'}`}>
                          {/* 1. Order Number */}
                          <td className="py-3.5 px-4 font-bold text-slate-900 font-mono whitespace-nowrap">
                            <div className="flex items-center space-x-2">
                              <span>{orderNumber}</span>
                              {job.isClosed ? (
                                <span className="text-[9px] bg-slate-100 text-slate-600 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Closed
                                </span>
                              ) : (
                                <span className="text-[9px] bg-emerald-50 text-emerald-700 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Active
                                </span>
                              )}
                            </div>
                          </td>

                          {/* 2. Category / Item */}
                          <td className="py-3.5 px-4">
                            <div className="font-bold text-slate-900">{category}</div>
                            <div className="text-xs text-slate-500 font-medium mt-0.5">{garmentItem}</div>
                          </td>

                          {/* 3. Target Quantity / FOB */}
                          <td className="py-3.5 px-4 font-mono">
                            <div className="font-bold text-slate-900">{targetQty}</div>
                            <div className="text-xs font-bold text-emerald-700 mt-0.5">{targetFob}</div>
                          </td>

                          {/* 4. Accept Quantity / FOB */}
                          <td className="py-3.5 px-4 font-mono">
                            <div className={`font-bold ${isAccepted ? 'text-slate-900' : 'text-slate-400'}`}>
                              {acceptedQty}
                            </div>
                            <div className={`text-xs font-bold mt-0.5 ${isAccepted ? 'text-emerald-700' : 'text-slate-400'}`}>
                              {acceptedFob}
                            </div>
                          </td>

                          {/* 5. Proceed */}
                          <td className="py-3.5 px-4 text-center whitespace-nowrap">
                            {isJobProceed ? (
                              <div className="flex flex-col items-center justify-center text-center leading-tight space-y-0.5">
                                <span className="font-mono text-[11px] font-bold text-slate-800">{jobEmpCodeDisplay}</span>
                                <span className="text-[11px] font-semibold text-slate-700">{jobEmpNameDisplay}</span>
                                <span className="font-mono text-[10px] text-slate-500">{jobEmpPhoneDisplay}</span>
                              </div>
                            ) : (
                              <span className="text-[10px] bg-slate-100 text-slate-500 border border-slate-200 font-medium px-2.5 py-1 rounded-full font-mono uppercase inline-block">
                                Pending
                              </span>
                            )}
                          </td>

                          {/* 6. ACTION */}
                          <td className="py-3.5 px-4 text-center">
                            <div className="flex items-center justify-center space-x-2">
                              {/* Styled View Button */}
                              <button
                                onClick={() => setViewingDetailedJob(job)}
                                className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-3 py-1.5 rounded-lg transition shadow-xs flex items-center space-x-1.5 cursor-pointer"
                                title="View complete details of this sourcing request"
                              >
                                <Eye className="w-3.5 h-3.5" />
                                <span>View</span>
                              </button>

                              {/* Quotes button */}
                              <button
                                onClick={() => setViewingBidsJob(job)}
                                className="bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold px-2.5 py-1.5 rounded-lg transition cursor-pointer flex items-center space-x-1"
                                title="View supplier bids and quotes"
                              >
                                <span>Quotes</span>
                                <span className="bg-slate-700 text-white text-[10px] font-mono px-1.5 py-0.2 rounded-full">
                                  {bidCount}
                                </span>
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {activeSubTab === 'all-need-order' && (
        <div className="space-y-6">
          {/* Header for All Need Orders */}
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center px-2 gap-4">
            <div>
              <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400 font-mono">
                Global Capacity Marketplace ({displayAllNeedOrders.length})
              </h3>
              <p className="text-[11px] text-slate-500">
                Browse empty production lines posted by verified manufacturing facilities.
              </p>
            </div>
          </div>

          {displayAllNeedOrders.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-2xl p-12 text-center max-w-lg mx-auto space-y-4 shadow-sm">
              <div className="bg-slate-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-slate-400 border border-slate-100">
                <Building2 className="w-6 h-6" />
              </div>
              <div className="space-y-1">
                <p className="font-bold text-sm text-slate-800">No empty capacity listed yet</p>
                <p className="text-xs text-slate-500 max-w-xs mx-auto">
                  Factories have not listed any available sewing lines. If you own a factory, go to "Our Need Order" to list your capacity.
                </p>
              </div>
            </div>
          ) : (
            <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-slate-900 text-white text-[11px] font-mono uppercase tracking-wider">
                      <th className="py-3 px-4 font-bold">Order Number</th>
                      <th className="py-3 px-4 font-bold">Category / Item</th>
                      <th className="py-3 px-4 font-bold">Capacity Quantity</th>
                      <th className="py-3 px-4 font-bold">Accept Quantity / FOB</th>
                      <th className="py-3 px-4 font-bold text-center">Proceed</th>
                      <th className="py-3 px-4 font-bold text-center">ACTION</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 text-xs">
                    {displayAllNeedOrders.map(post => {
                      const quoteCount = post.quotes?.length || 0;
                      const approvedQuote = post.quotes?.find(q => q.status === 'Approved');
                      const isAccepted = Boolean(approvedQuote || (post as any).acceptedPrice || post.isClosed);
                      const isNeedProceed = Boolean(post.isProceed || (post as any).proceed_status === 'In Progress');
                      const hasUserSentProposal = checkUserHasSentProposal(post);
                      const isHighlighted = isAccepted || hasUserSentProposal;
                      
                      const postEmpCode = (post as any).assigned_employee_code || post.assigned_staff_id || (post as any).assigned_employee_id;
                      const postEmpName = post.assigned_employee_name;
                      const postEmpPhone = post.assigned_employee_phone || (post as any).assigned_employee_mobile;

                      const postEmpCodeDisplay = (!postEmpCode || postEmpCode.startsWith('user-')) ? 'EMP-20455' : postEmpCode;
                      const postEmpNameDisplay = postEmpName || 'Alex Mercer';
                      const postEmpPhoneDisplay = postEmpPhone || '+1234567890';
                      
                      const orderNumber = (post as any).order_number || post.order_number || post.id;
                      const category = post.category || 'N/A';
                      const garmentItem = post.garmentItem || 'N/A';
                      const capacityQty = `${(post.quantity || 0).toLocaleString()} Pcs`;
                      
                      const acceptedQty = isAccepted 
                        ? `${((post as any).acceptedQuantity || post.quantity || 0).toLocaleString()} Pcs` 
                        : '--';
                        
                      const acceptedFob = approvedQuote 
                        ? `৳${Number(approvedQuote.targetBudget || 0).toFixed(2)} / Pcs` 
                        : ((post as any).acceptedPrice 
                          ? `৳${Number((post as any).acceptedPrice).toFixed(2)} / Pcs` 
                          : '--');

                      return (
                        <tr key={post.id} className={`transition duration-150 ${isHighlighted ? 'bg-rose-50/80 hover:bg-rose-100/80' : 'hover:bg-slate-50/80'}`}>
                          {/* 1. Order Number */}
                          <td className="py-3.5 px-4 font-bold text-slate-900 font-mono whitespace-nowrap">
                            <div className="flex items-center space-x-2">
                              <span>{orderNumber}</span>
                              {post.isClosed ? (
                                <span className="text-[9px] bg-slate-100 text-slate-600 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Closed
                                </span>
                              ) : (
                                <span className="text-[9px] bg-emerald-50 text-emerald-700 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Active
                                </span>
                              )}
                              {hasUserSentProposal && (
                                <span className="text-[9px] bg-rose-100 text-rose-800 border border-rose-200 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                  Proposal Sent
                                </span>
                              )}
                            </div>
                          </td>

                          {/* 2. Category / Item */}
                          <td className="py-3.5 px-4">
                            <div className="font-bold text-slate-900">{category}</div>
                            <div className="text-xs text-slate-500 font-medium mt-0.5">{garmentItem}</div>
                          </td>

                          {/* 3. Capacity Quantity */}
                          <td className="py-3.5 px-4 font-mono">
                            <div className="font-bold text-slate-900">{capacityQty}</div>
                          </td>

                          {/* 4. Accept Quantity / FOB */}
                          <td className="py-3.5 px-4 font-mono">
                            <div className={`font-bold ${isAccepted ? 'text-slate-900' : 'text-slate-400'}`}>
                              {acceptedQty}
                            </div>
                            <div className={`text-xs font-bold mt-0.5 ${isAccepted ? 'text-emerald-700' : 'text-slate-400'}`}>
                              {acceptedFob}
                            </div>
                          </td>

                          {/* 5. Proceed */}
                          <td className="py-3.5 px-4 text-center whitespace-nowrap">
                            {isNeedProceed ? (
                              <div className="flex flex-col items-center justify-center text-center leading-tight space-y-0.5">
                                <span className="font-mono text-[11px] font-bold text-slate-800">{postEmpCodeDisplay}</span>
                                <span className="text-[11px] font-semibold text-slate-700">{postEmpNameDisplay}</span>
                                <span className="font-mono text-[10px] text-slate-500">{postEmpPhoneDisplay}</span>
                              </div>
                            ) : (
                              <span className="text-[10px] bg-slate-100 text-slate-500 border border-slate-200 font-medium px-2.5 py-1 rounded-full font-mono uppercase inline-block">
                                Pending
                              </span>
                            )}
                          </td>

                          {/* 6. ACTION */}
                          <td className="py-3.5 px-4 text-center">
                            <button
                              onClick={() => {
                                const myProposal = post.quotes?.find(q => q.userId === user?.id);
                                setShowQuotesModalPost(post);
                                if (myProposal && post.userId !== user?.id) {
                                  setReviewingProposalQuote(myProposal);
                                } else {
                                  setReviewingProposalQuote(null);
                                }
                              }}
                              className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-3.5 py-1.5 rounded-lg transition shadow-xs flex items-center space-x-1.5 cursor-pointer mx-auto"
                              title="View order details"
                            >
                              <Eye className="w-3.5 h-3.5" />
                              <span>View</span>
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {activeSubTab === 'our-need-order' && (
        <div className="space-y-6">
          {/* Header row with + Post Need Order button */}
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center px-2 gap-4 pb-2">
            <div>
              <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400 font-mono">
                My Empty Capacity Listings ({myNeedOrders.length})
              </h3>
              <p className="text-[11px] text-slate-500 mt-0.5">
                Manage your submitted factory sewing lines and empty slot posts. Keep these updated as lines fill.
              </p>
            </div>
            <button
              id="open-post-capacity-btn"
              onClick={handleOpenPostNeedModal}
              className="w-full sm:w-auto px-4 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-sm flex items-center justify-center space-x-2 cursor-pointer font-bold transition duration-150 text-xs text-center"
            >
              <span>+ Post Need Order</span>
            </button>
          </div>

          {/* User History list section */}
          <div>
            {myNeedOrders.length === 0 ? (
              <div className="bg-white border border-slate-200 rounded-2xl p-12 text-center max-w-lg mx-auto space-y-3 shadow-sm">
                <div className="bg-slate-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-slate-400 border border-slate-100 animate-pulse">
                  <Building2 className="w-6 h-6" />
                </div>
                <div>
                  <p className="font-bold text-sm text-slate-800">You haven't posted any capacity slots yet</p>
                  <p className="text-xs text-slate-500 max-w-xs mx-auto mt-1">
                    Once you submit the form, your empty slots will be listed here and in the public marketplace.
                  </p>
                </div>
              </div>
            ) : (
              <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse">
                    <thead>
                      <tr className="bg-slate-900 text-white text-[11px] font-mono uppercase tracking-wider">
                        <th className="py-3 px-4 font-bold">Order Number</th>
                        <th className="py-3 px-4 font-bold">Category / Item</th>
                        <th className="py-3 px-4 font-bold">Capacity Quantity</th>
                        <th className="py-3 px-4 font-bold">Accept Quantity / FOB</th>
                        <th className="py-3 px-4 font-bold text-center">Proceed</th>
                        <th className="py-3 px-4 font-bold text-center">ACTION</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100 text-xs">
                      {myNeedOrders.map(post => {
                        const quoteCount = post.quotes?.length || 0;
                        const approvedQuote = post.quotes?.find(q => q.status === 'Approved');
                        const isAccepted = Boolean(approvedQuote || (post as any).acceptedPrice || post.isClosed);
                        const isNeedProceed = Boolean(post.isProceed || (post as any).proceed_status === 'In Progress');
                        
                        const postEmpCode = (post as any).assigned_employee_code || post.assigned_staff_id || (post as any).assigned_employee_id;
                        const postEmpName = post.assigned_employee_name;
                        const postEmpPhone = post.assigned_employee_phone || (post as any).assigned_employee_mobile;

                        const postEmpCodeDisplay = (!postEmpCode || postEmpCode.startsWith('user-')) ? 'EMP-20455' : postEmpCode;
                        const postEmpNameDisplay = postEmpName || 'Alex Mercer';
                        const postEmpPhoneDisplay = postEmpPhone || '+1234567890';
                        
                        const orderNumber = (post as any).order_number || post.order_number || post.id;
                        const category = post.category || 'N/A';
                        const garmentItem = post.garmentItem || 'N/A';
                        const capacityQty = `${(post.quantity || 0).toLocaleString()} Pcs`;
                        
                        const acceptedQty = isAccepted 
                          ? `${((post as any).acceptedQuantity || post.quantity || 0).toLocaleString()} Pcs` 
                          : '--';
                          
                        const acceptedFob = approvedQuote 
                          ? `৳${Number(approvedQuote.targetBudget || 0).toFixed(2)} / Pcs` 
                          : ((post as any).acceptedPrice 
                            ? `৳${Number((post as any).acceptedPrice).toFixed(2)} / Pcs` 
                            : '--');

                        return (
                          <tr key={post.id} className={`transition duration-150 ${isAccepted ? 'bg-rose-50/80 hover:bg-rose-100/80' : 'hover:bg-slate-50/80'}`}>
                            {/* 1. Order Number */}
                            <td className="py-3.5 px-4 font-bold text-slate-900 font-mono whitespace-nowrap">
                              <div className="flex items-center space-x-2">
                                <span>{orderNumber}</span>
                                {post.isClosed ? (
                                  <span className="text-[9px] bg-slate-100 text-slate-600 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                    Closed
                                  </span>
                                ) : (
                                  <span className="text-[9px] bg-emerald-50 text-emerald-700 font-bold px-2 py-0.5 rounded-full font-mono uppercase">
                                    Active
                                  </span>
                                )}
                              </div>
                            </td>

                            {/* 2. Category / Item */}
                            <td className="py-3.5 px-4">
                              <div className="font-bold text-slate-900">{category}</div>
                              <div className="text-xs text-slate-500 font-medium mt-0.5">{garmentItem}</div>
                            </td>

                            {/* 3. Capacity Quantity */}
                            <td className="py-3.5 px-4 font-mono">
                              <div className="font-bold text-slate-900">{capacityQty}</div>
                            </td>

                            {/* 4. Accept Quantity / FOB */}
                            <td className="py-3.5 px-4 font-mono">
                              <div className={`font-bold ${isAccepted ? 'text-slate-900' : 'text-slate-400'}`}>
                                {acceptedQty}
                              </div>
                              <div className={`text-xs font-bold mt-0.5 ${isAccepted ? 'text-emerald-700' : 'text-slate-400'}`}>
                                {acceptedFob}
                              </div>
                            </td>

                            {/* 5. Proceed */}
                            <td className="py-3.5 px-4 text-center whitespace-nowrap">
                              {isNeedProceed ? (
                                <div className="flex flex-col items-center justify-center text-center leading-tight space-y-0.5">
                                  <span className="font-mono text-[11px] font-bold text-slate-800">{postEmpCodeDisplay}</span>
                                  <span className="text-[11px] font-semibold text-slate-700">{postEmpNameDisplay}</span>
                                  <span className="font-mono text-[10px] text-slate-500">{postEmpPhoneDisplay}</span>
                                </div>
                              ) : (
                                <span className="text-[10px] bg-slate-100 text-slate-500 border border-slate-200 font-medium px-2.5 py-1 rounded-full font-mono uppercase inline-block">
                                  Pending
                                </span>
                              )}
                            </td>

                            {/* 6. ACTION */}
                            <td className="py-3.5 px-4 text-center">
                              <button
                                onClick={() => {
                                  setShowQuotesModalPost(post);
                                  const approvedQuote = post.quotes?.find(q => q.status === 'Approved');
                                  if (approvedQuote) {
                                    setReviewingProposalQuote(approvedQuote);
                                  } else {
                                    setReviewingProposalQuote(null);
                                  }
                                }}
                                className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-3.5 py-1.5 rounded-lg transition shadow-xs flex items-center space-x-1.5 cursor-pointer mx-auto"
                                title="View order details and quotes"
                              >
                                <Eye className="w-3.5 h-3.5" />
                                <span>View &amp; Quotes</span>
                                <span className="bg-blue-800 text-white text-[10px] font-mono px-1.5 py-0.2 rounded-full">
                                  {quoteCount}
                                </span>
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* MODAL 1: POST SOURCE ORDER FORM */}
      {showPostJobModal && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-2xl w-full overflow-hidden my-8">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="flex items-center space-x-2">
                <Shirt className="w-5 h-5 text-blue-400" />
                <div>
                  <h3 className="font-sans font-bold text-sm sm:text-base">Post Garments Sourcing Order</h3>
                  <p className="text-[10px] text-slate-400">Specify garment merchandiser criteria & spec sheets</p>
                </div>
              </div>
              <button 
                onClick={() => setShowPostJobModal(false)}
                className="text-slate-400 hover:text-white text-xl cursor-pointer font-bold px-1.5"
              >
                &times;
              </button>
            </div>

            <form onSubmit={handlePostJobSubmit} className="p-6 space-y-5 max-h-[80vh] overflow-y-auto">
              
              {/* Row 1: Style Name */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700">Style Name / Number *</label>
                <input 
                  type="text"
                  required
                  placeholder="e.g. Slim Fit Denim Jacket, Basic Crewneck Tee"
                  value={styleNumber}
                  onChange={(e) => setStyleNumber(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition"
                />
              </div>

              {/* Row 2: Category & Garment Item */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Garment Category *</label>
                  <select
                    value={category}
                    onChange={(e) => setCategory(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2.5 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition"
                  >
                    {availableCategoryOptions.map(cat => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                  </select>
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Garment Item *</label>
                  <select
                    value={garmentItem}
                    onChange={(e) => setGarmentItem(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2.5 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition"
                  >
                    {availableItemOptions.map(itm => (
                      <option key={itm} value={itm}>{itm}</option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Row 3: Volume & Commercials */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Target Quantity (Pcs) *</label>
                  <input 
                    type="number"
                    required
                    min="1"
                    placeholder="e.g. 20000"
                    value={quantity}
                    onChange={(e) => setQuantity(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition font-mono"
                  />
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Target FOB Price (BDT/Pcs) *</label>
                  <div className="relative">
                    <span className="absolute left-3.5 top-3 text-slate-400 text-xs sm:text-sm font-semibold">৳</span>
                    <input 
                      type="number"
                      step="0.01"
                      min="0.01"
                      required
                      placeholder="e.g. 5.80"
                      value={fobBudget}
                      onChange={(e) => setFobBudget(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg pl-7 pr-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition font-mono"
                    />
                  </div>
                </div>
              </div>

              {/* Row 3: Industrial Tech Specs */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">SMV (Standard Minute Value) *</label>
                  <input 
                    type="number"
                    step="0.1"
                    min="0.1"
                    required
                    placeholder="e.g. 15.5"
                    value={smv}
                    onChange={(e) => setSmv(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition font-mono"
                  />
                  <span className="text-[9px] text-slate-400">Total manufacturing target standard minutes</span>
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Number of Colors *</label>
                  <input 
                    type="number"
                    min="1"
                    required
                    placeholder="e.g. 3"
                    value={colorsCount}
                    onChange={(e) => setColorsCount(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition font-mono"
                  />
                  <span className="text-[9px] text-slate-400">Style colorways breakdown</span>
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Number of PO (Purchase Orders) *</label>
                  <input 
                    type="number"
                    min="1"
                    required
                    placeholder="e.g. 2"
                    value={poCount}
                    onChange={(e) => setPoCount(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition font-mono"
                  />
                  <span className="text-[9px] text-slate-400">Distinct shipments / delivery schedules</span>
                </div>
              </div>

              {/* Row 4: Shipping date */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700">Target Shipping Date *</label>
                <input 
                  type="date"
                  required
                  value={targetDate}
                  onChange={(e) => setTargetDate(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition"
                />
              </div>

              {/* Garment Media Uploads (NEW) */}
              <div className="bg-slate-50 border border-slate-200 p-4 rounded-xl space-y-4">
                <div className="flex items-center space-x-2 border-b border-slate-200 pb-2">
                  <Shirt className="w-4 h-4 text-blue-600" />
                  <h4 className="text-xs font-bold uppercase tracking-wider text-slate-800 font-mono">
                    Garment Media Uploads
                  </h4>
                </div>

                {mediaError && (
                  <div className="bg-red-50 text-red-700 border border-red-150 rounded-lg p-3 text-xs flex items-center space-x-2">
                    <span className="font-bold text-base leading-none">&times;</span>
                    <span>{mediaError}</span>
                  </div>
                )}

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {/* Images upload (Max 4) */}
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <label className="block text-xs font-bold text-slate-700">Product Images (Max 4)</label>
                      <span className="text-[10px] font-mono text-slate-500">{uploadedImages.length} / 4 uploaded</span>
                    </div>
                    <div className="border-2 border-dashed border-slate-300 rounded-xl p-4 text-center hover:bg-slate-100/50 transition relative">
                      <input 
                        type="file"
                        multiple
                        accept=".jpg,.jpeg,.png,.webp"
                        onChange={handleImageUpload}
                        disabled={uploadedImages.length >= 4}
                        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
                      />
                      <div className="space-y-1">
                        <Plus className="w-5 h-5 text-slate-400 mx-auto" />
                        <p className="text-[11px] text-slate-500 font-semibold">Click or drag images here</p>
                        <p className="text-[9px] text-slate-400">JPG, JPEG, PNG, WEBP formats</p>
                      </div>
                    </div>

                    {/* Image thumbnails list with remove action */}
                    {uploadedImages.length > 0 && (
                      <div className="grid grid-cols-4 gap-2 mt-2">
                        {uploadedImages.map((img, idx) => (
                          <div key={idx} className="relative group aspect-square rounded-lg overflow-hidden border border-slate-200 bg-slate-100">
                            <img src={img} alt={`Sample ${idx+1}`} className="w-full h-full object-cover" />
                            <button
                              type="button"
                              onClick={() => removeImage(idx)}
                              className="absolute top-1 right-1 bg-red-600 hover:bg-red-700 text-white rounded-full p-0.5 shadow-md hover:scale-105 transition"
                              title="Remove image"
                            >
                              <span className="block text-[10px] leading-none px-1 font-bold">&times;</span>
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>

                  {/* Video upload (Max 1) */}
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <label className="block text-xs font-bold text-slate-700">Product Video (Max 1)</label>
                      <span className="text-[10px] font-mono text-slate-500">{uploadedVideo ? 1 : 0} / 1 uploaded</span>
                    </div>
                    <div className="border-2 border-dashed border-slate-300 rounded-xl p-4 text-center hover:bg-slate-100/50 transition relative">
                      <input 
                        type="file"
                        accept=".mp4,.mov"
                        onChange={handleVideoUpload}
                        disabled={!!uploadedVideo}
                        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
                      />
                      <div className="space-y-1">
                        <Plus className="w-5 h-5 text-slate-400 mx-auto" />
                        <p className="text-[11px] text-slate-500 font-semibold">Click or drag video here</p>
                        <p className="text-[9px] text-slate-400">MP4, MOV formats</p>
                      </div>
                    </div>

                    {/* Video preview with remove action */}
                    {uploadedVideo && (
                      <div className="relative mt-2 rounded-lg overflow-hidden border border-slate-200 bg-black aspect-video flex items-center justify-center">
                        <video src={uploadedVideo} controls className="w-full h-full object-contain max-h-[100px]" />
                        <button
                          type="button"
                          onClick={removeVideo}
                          className="absolute top-1 right-1 bg-red-600 hover:bg-red-700 text-white rounded-full p-0.5 shadow-md hover:scale-105 transition z-10"
                          title="Remove video"
                        >
                          <span className="block text-[10px] leading-none px-1 font-bold">&times;</span>
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Row 5: Spec details */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700 font-sans">Detailed Fabric & Spec Description *</label>
                <textarea 
                  required
                  rows={4}
                  placeholder="e.g. Fabric blend (e.g. 100% Cotton, 80/20 CVC), yarn counts, specific GSM (e.g. 180 GSM, 400 GSM fleece), sewing guidelines, measurement size charts, special washes, or packaging codes..."
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none focus:border-transparent transition"
                />
              </div>

              <div className="pt-4 border-t border-slate-100 flex justify-end space-x-3 text-xs font-semibold">
                <button 
                  type="button"
                  onClick={() => setShowPostJobModal(false)}
                  className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="px-4 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white shadow-md cursor-pointer flex items-center space-x-1.5"
                >
                  <Sparkles className="w-4 h-4" />
                  <span>Post Sourcing Order</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: APPLY FOR CONTRACT (MANUFACTURING QUOTE) */}
      {showApplyModal && selectedJob && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-md w-full overflow-hidden">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="space-y-0.5">
                <h3 className="font-sans font-bold text-sm sm:text-base">Submit Manufacturing Quote</h3>
                <p className="text-[10px] text-slate-400 truncate max-w-[320px]">
                  Applying for Order: Style {selectedJob.styleNumber || selectedJob.title}
                </p>
              </div>
              <button 
                onClick={() => {
                  setShowApplyModal(false);
                  setSelectedJob(null);
                }}
                className="text-slate-400 hover:text-white text-lg cursor-pointer"
              >
                &times;
              </button>
            </div>

            {/* Validation warning block if no approved factories */}
            {!hasApprovedFactory ? (
              <div className="p-6 text-center space-y-4">
                <div className="bg-amber-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-amber-500 border border-amber-100 animate-pulse">
                  <AlertTriangle className="w-6 h-6" />
                </div>
                <div className="space-y-2">
                  <p className="text-sm font-bold text-slate-800">No Approved Factories Linked</p>
                  <p className="text-xs text-slate-500 max-w-xs mx-auto leading-relaxed">
                    Under standard compliance rules, <strong className="text-amber-700">you can only link an Admin-Approved factory</strong> to an order bid. 
                  </p>
                  <p className="text-[11px] text-slate-400 max-w-xs mx-auto leading-normal">
                    Please navigate to <strong className="text-slate-600">My Factories</strong> to check registration status or wait for the Administrator to approve your submitted Trade Licenses.
                  </p>
                </div>
                <div className="pt-2">
                  <button 
                    onClick={() => {
                      setShowApplyModal(false);
                      setSelectedJob(null);
                    }}
                    className="text-xs font-bold text-slate-700 bg-slate-100 hover:bg-slate-200 px-4 py-2 rounded-lg cursor-pointer"
                  >
                    Got It, Close
                  </button>
                </div>
              </div>
            ) : (
              <form onSubmit={handleApplySubmit} className="p-6 space-y-4">
                {/* Factory selection dropdown with approved restriction */}
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Select Production Factory *</label>
                  <select
                    required
                    value={selectedFactoryId}
                    onChange={(e) => setSelectedFactoryId(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2.5 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  >
                    <option value="">-- Choose your Approved factory --</option>
                    {approvedFactories.map(f => (
                      <option key={f.id} value={f.id}>
                        {f.name} ({f.type} &bull; Approved)
                      </option>
                    ))}
                  </select>
                  <div className="flex items-center space-x-1.5 mt-1.5">
                    <CheckCircle className="w-3.5 h-3.5 text-emerald-600" />
                    <span className="text-[10px] text-emerald-700 font-semibold block">Only Admin-Approved factories are selectable.</span>
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Your Price Quote / Unit Bid (BDT/Pcs) *</label>
                  <div className="relative">
                    <span className="absolute left-3.5 top-3 text-slate-400 text-xs">৳</span>
                    <input 
                      type="text"
                      required
                      placeholder="e.g. 5.15"
                      value={priceBid}
                      onChange={(e) => setPriceBid(e.target.value)}
                      className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg pl-7 pr-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono"
                    />
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700">Sourcing Proposal & Cover Note *</label>
                  <textarea 
                    required
                    rows={4}
                    placeholder="Specify target lead-times, line allocation, testing capabilities, standard washing compliance, and custom remarks..."
                    value={coverNote}
                    onChange={(e) => setCoverNote(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div className="pt-4 border-t border-slate-100 flex justify-end space-x-3 text-xs font-semibold">
                  <button 
                    type="button"
                    onClick={() => {
                      setShowApplyModal(false);
                      setSelectedJob(null);
                    }}
                    className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit"
                    className="px-4 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white shadow-sm flex items-center space-x-1.5 cursor-pointer"
                  >
                    <Send className="w-3.5 h-3.5" />
                    <span>Submit Manufacturing Bid</span>
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}

      {/* MODAL 3: POST CAPACITY / NEED ORDER FORM */}
      {showPostNeedModal && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-md w-full overflow-hidden">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="space-y-0.5">
                <h3 className="font-sans font-bold text-sm sm:text-base">
                  {editingNeedOrderId ? "Edit Factory Empty Capacity" : "Post Factory Empty Capacity"}
                </h3>
                <p className="text-[10px] text-slate-400">
                  {editingNeedOrderId ? "Update your empty sewing lines and available space details." : "Notify order holders about your empty sewing lines and available space."}
                </p>
              </div>
              <button 
                onClick={() => {
                  setShowPostNeedModal(false);
                }}
                className="text-slate-400 hover:text-white text-lg cursor-pointer"
              >
                &times;
              </button>
            </div>

            {/* Validation warning block if no approved factories */}
            {!hasApprovedFactory ? (
              <div className="p-6 text-center space-y-4">
                <div className="bg-amber-50 p-4 rounded-full w-14 h-14 flex items-center justify-center mx-auto text-amber-500 border border-amber-100 animate-pulse">
                  <AlertTriangle className="w-6 h-6" />
                </div>
                <div className="space-y-2">
                  <p className="text-sm font-bold text-slate-800">No Approved Factories Linked</p>
                  <p className="text-xs text-slate-500 max-w-xs mx-auto leading-relaxed">
                    Under B2B security protocols, <strong className="text-amber-700">you can only post empty capacities for an Admin-Approved factory</strong>. 
                  </p>
                  <p className="text-[11px] text-slate-400 max-w-xs mx-auto leading-normal">
                    Please go to <strong className="text-slate-600">My Factories</strong> to check registration status or wait for the Administrator to approve your submitted Trade Licenses.
                  </p>
                </div>
                <div className="pt-2">
                  <button 
                    onClick={() => {
                      setShowPostNeedModal(false);
                    }}
                    className="text-xs font-bold text-slate-700 bg-slate-100 hover:bg-slate-200 px-4 py-2 rounded-lg cursor-pointer"
                  >
                    Got It, Close
                  </button>
                </div>
              </div>
            ) : (
              <form onSubmit={handlePostNeedOrderSubmit} className="p-6 space-y-4">
                {/* Factory selection dropdown with approved restriction */}
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700 font-sans">Select Capable Factory *</label>
                  <select
                    required
                    value={needFactoryId}
                    onChange={(e) => setNeedFactoryId(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2.5 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  >
                    <option value="">-- Choose your Approved factory --</option>
                    {approvedFactories.map(f => (
                      <option key={f.id} value={f.id}>
                        {f.name} ({f.type} &bull; Approved)
                      </option>
                    ))}
                  </select>
                  <div className="flex items-center space-x-1.5 mt-1.5">
                    <CheckCircle className="w-3.5 h-3.5 text-emerald-600" />
                    <span className="text-[10px] text-emerald-700 font-semibold block">Only Admin-Approved factories are selectable.</span>
                  </div>
                </div>

                {/* Garment Category dropdown */}
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700 font-sans">Garment Category *</label>
                  <select
                    required
                    value={needCategory}
                    onChange={(e) => setNeedCategory(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2.5 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none transition font-sans"
                  >
                    {availableCategoryOptions.map(cat => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                  </select>
                </div>

                {/* Garment Item dropdown */}
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700 font-sans">Garment Item *</label>
                  <select
                    required
                    value={needGarmentItem}
                    onChange={(e) => setNeedGarmentItem(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3 py-2.5 bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none transition font-sans"
                  >
                    {availableItemOptions.map(itm => (
                      <option key={itm} value={itm}>{itm}</option>
                    ))}
                  </select>
                </div>

                {/* Production Quantity Capacity */}
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700 font-sans">Production Quantity Capacity (Pcs) *</label>
                  <input 
                    type="number"
                    required
                    min={100}
                    placeholder="e.g. 50000"
                    value={needQuantity}
                    onChange={(e) => setNeedQuantity(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono"
                  />
                  <p className="text-[10px] text-slate-400">Minimum 100 pieces.</p>
                </div>

                {/* Sewing Start Date */}
                <div className="space-y-1">
                  <label className="block text-xs font-bold text-slate-700 font-sans">Sewing Start Date *</label>
                  <input 
                    type="date"
                    required
                    value={needSewingStartDate}
                    onChange={(e) => setNeedSewingStartDate(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-sans"
                  />
                  <p className="text-[10px] text-slate-400">Select the date sewing lines become empty.</p>
                </div>

                <div className="pt-4 border-t border-slate-100 flex justify-end space-x-3 text-xs font-semibold">
                  <button 
                    type="button"
                    onClick={() => {
                      setShowPostNeedModal(false);
                    }}
                    className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit"
                    className="px-4 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white shadow-sm flex items-center space-x-1.5 cursor-pointer font-bold"
                  >
                    <Send className="w-3.5 h-3.5" />
                    <span>{editingNeedOrderId ? "Save Capacity Changes" : "Post Available Capacity"}</span>
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}

      {/* MODAL 2.5: DETAILED ORDER VIEW MODAL */}
      {viewingDetailedJob && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-3xl w-full overflow-hidden my-8">
            {/* Modal Header */}
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="flex items-center space-x-2.5">
                <Shirt className="w-5 h-5 text-blue-400" />
                <div>
                  <h3 className="font-sans font-bold text-sm sm:text-base">Style Details & Spec Sheet</h3>
                  <p className="text-[10px] text-slate-400">Review technical requirements before placing a manufacturing bid</p>
                </div>
              </div>
              <button 
                onClick={() => setViewingDetailedJob(null)}
                className="text-slate-400 hover:text-white text-xl cursor-pointer font-bold px-1.5"
              >
                &times;
              </button>
            </div>

            {/* Modal Content */}
            <div className="p-6 space-y-6 max-h-[75vh] overflow-y-auto">
              {/* Header Info */}
              <div className="flex flex-wrap items-center justify-between gap-3 pb-4 border-b border-slate-100">
                <div className="space-y-1">
                  <div className="flex items-center space-x-2">
                    <span className="text-[10px] bg-blue-50 text-blue-700 border border-blue-100 font-bold px-2.5 py-0.5 rounded-full">
                      {viewingDetailedJob.category} / {viewingDetailedJob.garmentItem || 'N/A'}
                    </span>
                    <span className="text-[10px] text-slate-400 font-mono flex items-center">
                      <Building2 className="w-3.5 h-3.5 mr-1" /> Posted by {viewingDetailedJob.userName}
                    </span>
                  </div>
                  <h2 className="text-lg font-bold text-slate-900 font-sans tracking-tight">
                    Style/Number: <span className="text-blue-600">{viewingDetailedJob.styleNumber || viewingDetailedJob.title}</span>
                  </h2>
                </div>

                {/* Action buttons inside detailed view */}
                {viewingDetailedJob.userId === user?.id || user?.role === 'Admin' ? (
                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => {
                        const jobToBids = viewingDetailedJob;
                        setViewingDetailedJob(null);
                        setViewingBidsJob(jobToBids);
                      }}
                      className="bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold px-3 py-2 rounded-xl transition cursor-pointer flex items-center space-x-1.5"
                    >
                      <span>Quotes</span>
                      <span className="bg-slate-700 text-white text-[10px] font-mono px-1.5 py-0.2 rounded-full">
                        {viewingDetailedJob.bids?.length || 0}
                      </span>
                    </button>
                    {(viewingDetailedJob.bids?.length || 0) === 0 && !viewingDetailedJob.isClosed && (
                      <>
                        <button
                          onClick={() => {
                            const jobToEdit = viewingDetailedJob;
                            setViewingDetailedJob(null);
                            handleStartEditJob(jobToEdit);
                          }}
                          className="bg-blue-50 hover:bg-blue-100 text-blue-700 text-xs font-bold px-3 py-2 rounded-xl transition cursor-pointer flex items-center space-x-1"
                        >
                          <Pencil className="w-3.5 h-3.5" />
                          <span>Edit</span>
                        </button>
                        <button
                          onClick={() => {
                            const idToDelete = viewingDetailedJob.id;
                            setViewingDetailedJob(null);
                            if (onDeleteJob) onDeleteJob(idToDelete);
                          }}
                          className="bg-red-50 hover:bg-red-100 text-red-700 text-xs font-bold px-3 py-2 rounded-xl transition cursor-pointer flex items-center space-x-1"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                          <span>Delete</span>
                        </button>
                      </>
                    )}
                  </div>
                ) : checkUserHasApplied(viewingDetailedJob) ? (
                  <div className="bg-slate-100 text-slate-600 border border-slate-200 text-xs font-bold px-4 py-2.5 rounded-xl flex items-center space-x-1.5 font-sans select-none">
                    <CheckCircle className="w-4 h-4 text-emerald-600" />
                    <span>Already Applied</span>
                  </div>
                ) : (
                  <button
                    onClick={() => {
                      setSelectedJob(viewingDetailedJob);
                      setViewingDetailedJob(null); // Close detail modal
                      setShowApplyModal(true); // Open apply modal
                    }}
                    className="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold px-5 py-3 rounded-xl shadow-sm transition duration-150 cursor-pointer text-center flex items-center space-x-1.5"
                  >
                    <Send className="w-4 h-4" />
                    <span>Apply & Quote Now</span>
                  </button>
                )}
              </div>

              {/* Specs Grid (SMV, Deadline, Colorways, POs, target quantity, FOB target, category, garmentItem) */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Garment Category</p>
                  <p className="text-sm font-bold text-slate-800 mt-0.5">{viewingDetailedJob.category}</p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Garment Item</p>
                  <p className="text-sm font-bold text-slate-800 mt-0.5">{viewingDetailedJob.garmentItem || 'N/A'}</p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Target Quantity</p>
                  <p className="text-sm font-bold text-slate-800 font-mono mt-0.5">{(viewingDetailedJob.quantity || 0).toLocaleString()} Pcs</p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Target FOB Budget</p>
                  <p className="text-sm font-bold text-emerald-700 font-mono mt-0.5">
                    {viewingDetailedJob.fobBudget ? `৳${viewingDetailedJob.fobBudget.toFixed(2)} / Pcs` : viewingDetailedJob.budget}
                  </p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Standard SMV</p>
                  <p className="text-sm font-bold text-slate-800 font-mono mt-0.5">{viewingDetailedJob.smv || '--'} Min</p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Shipment Deadline</p>
                  <p className="text-sm font-bold text-slate-800 font-mono mt-0.5">
                    {new Date(viewingDetailedJob.targetDate).toLocaleDateString([], {month: 'short', day: 'numeric', year: 'numeric'})}
                  </p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Colorways Count</p>
                  <p className="text-sm font-bold text-slate-800 font-mono mt-0.5">{viewingDetailedJob.colorsCount || '--'} Colors</p>
                </div>
                <div className="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                  <p className="text-[10px] text-slate-400 font-mono uppercase font-bold">Purchase Orders</p>
                  <p className="text-sm font-bold text-slate-800 font-mono mt-0.5">{viewingDetailedJob.poCount || '--'} POs / Deliveries</p>
                </div>
              </div>

              {/* Media Gallery Block */}
              {((viewingDetailedJob.images && viewingDetailedJob.images.length > 0) || viewingDetailedJob.videoUrl) && (
                <div className="bg-slate-50 border border-slate-200 p-4 rounded-xl space-y-4">
                  <h4 className="text-xs uppercase font-mono tracking-wider font-bold text-slate-700 flex items-center">
                    <Sparkles className="w-3.5 h-3.5 mr-1 text-blue-500" /> Garment Techpack & Sample Media
                  </h4>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Images Column */}
                    {viewingDetailedJob.images && viewingDetailedJob.images.length > 0 && (
                      <div className="space-y-2">
                        <span className="text-[10px] text-slate-500 font-bold uppercase tracking-wider block">Sample Photos ({viewingDetailedJob.images.length})</span>
                        <div className="grid grid-cols-2 gap-2">
                          {viewingDetailedJob.images.map((img, idx) => (
                            <div 
                              key={idx} 
                              onClick={() => setLightboxImage(img)}
                              className="aspect-square rounded-lg overflow-hidden border border-slate-200 bg-white cursor-zoom-in hover:opacity-90 active:scale-95 transition shadow-sm"
                            >
                              <img src={img} alt="Product Thumbnail" className="w-full h-full object-cover" referrerPolicy="no-referrer" />
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Video Column */}
                    {viewingDetailedJob.videoUrl && (
                      <div className="space-y-2">
                        <span className="text-[10px] text-slate-500 font-bold uppercase tracking-wider block">Technical Video Demonstration</span>
                        <div className="rounded-lg overflow-hidden border border-slate-200 bg-black aspect-video flex items-center justify-center w-full shadow-sm">
                          <video src={viewingDetailedJob.videoUrl} controls preload="metadata" className="w-full h-full object-contain" />
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Fabric & Spec Instructions */}
              <div className="bg-slate-50 border border-slate-150 p-4 rounded-xl space-y-2">
                <h4 className="text-xs uppercase font-mono tracking-wider font-bold text-slate-700 flex items-center">
                  <FileText className="w-3.5 h-3.5 mr-1 text-slate-500" /> Fabric & Spec Instructions
                </h4>
                <p className="text-xs text-slate-600 leading-relaxed whitespace-pre-line bg-white p-3 rounded-lg border border-slate-100 shadow-inner">
                  {viewingDetailedJob.description}
                </p>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="px-6 py-4 bg-slate-50 border-t border-slate-100 flex items-center justify-between text-xs font-semibold">
              <button 
                type="button"
                onClick={() => setViewingDetailedJob(null)}
                className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-100 cursor-pointer transition"
              >
                Close Specs
              </button>

              {viewingDetailedJob.userId === user?.id || user?.role === 'Admin' ? (
                <div className="flex items-center space-x-2">
                  {(viewingDetailedJob.bids?.length || 0) === 0 && !viewingDetailedJob.isClosed && (
                    <>
                      <button
                        onClick={() => {
                          const jobToEdit = viewingDetailedJob;
                          setViewingDetailedJob(null);
                          handleStartEditJob(jobToEdit);
                        }}
                        className="px-4 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-bold cursor-pointer transition flex items-center space-x-1.5"
                      >
                        <Pencil className="w-4 h-4" />
                        <span>Edit Order</span>
                      </button>
                      <button
                        onClick={() => {
                          const idToDelete = viewingDetailedJob.id;
                          setViewingDetailedJob(null);
                          if (onDeleteJob) onDeleteJob(idToDelete);
                        }}
                        className="px-4 py-2.5 rounded-lg bg-red-600 hover:bg-red-700 text-white font-bold cursor-pointer transition flex items-center space-x-1.5"
                      >
                        <Trash2 className="w-4 h-4" />
                        <span>Delete Order</span>
                      </button>
                    </>
                  )}
                </div>
              ) : checkUserHasApplied(viewingDetailedJob) ? (
                <div className="bg-slate-100 text-slate-600 border border-slate-200 text-xs font-bold px-4 py-2 rounded-lg flex items-center space-x-1.5 font-sans select-none">
                  <CheckCircle className="w-4 h-4 text-emerald-600" />
                  <span>Already Applied</span>
                </div>
              ) : (
                <button 
                  onClick={() => {
                    setSelectedJob(viewingDetailedJob);
                    setViewingDetailedJob(null);
                    setShowApplyModal(true);
                  }}
                  className="px-5 py-2.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white shadow-md cursor-pointer flex items-center space-x-1.5"
                >
                  <Send className="w-4 h-4" />
                  <span>Apply & Quote Now</span>
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* LIGHTBOX MODAL */}
      {lightboxImage && (
        <div 
          onClick={() => setLightboxImage(null)}
          className="fixed inset-0 bg-slate-950/80 flex items-center justify-center p-4 z-[100] cursor-zoom-out"
        >
          <div className="relative max-w-4xl max-h-[90vh] bg-transparent overflow-hidden rounded-xl">
            <img src={lightboxImage} alt="Enlarged garment preview" className="w-full h-auto max-h-[85vh] object-contain rounded-xl" />
            <button 
              onClick={() => setLightboxImage(null)}
              className="absolute top-3 right-3 bg-slate-900/80 hover:bg-black text-white rounded-full w-8 h-8 flex items-center justify-center text-xl font-bold font-sans cursor-pointer"
            >
              &times;
            </button>
          </div>
        </div>
      )}

      {/* MODAL 4: BID & QUOTATION MANAGEMENT MODAL */}
      {viewingBidsJob && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-3xl w-full overflow-hidden my-8">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="flex items-center space-x-2.5">
                <ClipboardList className="w-5 h-5 text-blue-400" />
                <div>
                  <h3 className="font-sans font-bold text-sm sm:text-base">Incoming Quotations / Bids</h3>
                  <p className="text-[10px] text-slate-400">Review, inspect, and accept quotations for Style: {viewingBidsJob.styleNumber || viewingBidsJob.title}</p>
                </div>
              </div>
              <button 
                onClick={() => setViewingBidsJob(null)}
                className="text-slate-400 hover:text-white text-xl cursor-pointer font-bold px-1.5"
              >
                &times;
              </button>
            </div>

            <div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
              {viewingBidsJob.isClosed && (
                <div className="bg-amber-50 text-amber-800 border border-amber-150 rounded-xl p-4 text-xs flex items-start space-x-2">
                  <Info className="w-4 h-4 text-amber-600 mt-0.5 shrink-0" />
                  <div>
                    <span className="font-bold block">Sourcing Request Closed</span>
                    <span>An agreement has already been reached for this order. You can still inspect the quotation details below, but no further bids can be accepted.</span>
                  </div>
                </div>
              )}

              {(!viewingBidsJob.bids || viewingBidsJob.bids.length === 0) ? (
                <div className="text-center py-12 space-y-3 bg-slate-50 rounded-2xl border border-slate-150 max-w-md mx-auto my-4">
                  <div className="bg-white p-3 rounded-full w-12 h-12 flex items-center justify-center mx-auto text-slate-400 shadow-sm border border-slate-100">
                    <Inbox className="w-5 h-5" />
                  </div>
                  <div>
                    <p className="text-sm font-bold text-slate-800">No quotes received yet</p>
                    <p className="text-xs text-slate-500 max-w-xs mx-auto">This order is active on the public feed. When suppliers submit quotes, they will appear here instantly with their factory details.</p>
                  </div>
                </div>
              ) : (
                <div className="space-y-4">
                  <h4 className="text-[10px] uppercase font-mono tracking-wider font-bold text-slate-400">
                    Received Quotations ({viewingBidsJob.bids.length})
                  </h4>

                  <div className="space-y-4">
                    {viewingBidsJob.bids.map(app => {
                      const isApproved = app.status === 'Approved';
                      const isRejected = app.status === 'Rejected';
                      return (
                        <div 
                          key={app.id} 
                          className={`border rounded-2xl p-5 shadow-sm transition flex flex-col justify-between gap-4 ${
                            isApproved 
                              ? 'border-emerald-300 bg-emerald-50/20' 
                              : isRejected 
                              ? 'border-slate-200 bg-slate-50/40 opacity-75' 
                              : 'border-slate-200 bg-white hover:border-slate-300'
                          }`}
                        >
                          <div className="flex flex-col sm:flex-row justify-between items-start gap-4">
                            <div className="space-y-1">
                              <div className="flex items-center space-x-2">
                                <span className="font-bold text-sm text-slate-950 font-sans leading-none block">
                                  {app.factoryName || app.userName}
                                </span>
                                {isApproved && (
                                  <span className="bg-emerald-100 text-emerald-800 font-bold font-mono text-[9px] px-2 py-0.5 rounded-full flex items-center">
                                    <CheckCircle className="w-3 h-3 mr-1" /> Accepted Quote
                                  </span>
                                )}
                                {isRejected && (
                                  <span className="bg-slate-100 text-slate-500 font-bold font-mono text-[9px] px-2 py-0.5 rounded-full">
                                    Closed
                                  </span>
                                )}
                              </div>
                              {/* Phone display permanently hidden as per strict privacy rules */}
                            </div>

                            <div className="bg-slate-50 border border-slate-150 px-4 py-2 rounded-xl text-right shrink-0">
                              <span className="text-[9px] font-mono font-bold text-slate-400 block uppercase">PROPOSED FOB (BDT)</span>
                              <span className="font-mono font-bold text-emerald-700 text-sm sm:text-base">
                                ৳{Number(app.priceBid).toFixed(2)} / pc
                              </span>
                            </div>
                          </div>

                          <div className="bg-slate-50/50 p-3.5 rounded-xl border border-slate-100">
                            <p className="text-[9px] font-mono font-bold text-slate-400 uppercase mb-1">Supplier Proposal / Cover Letter</p>
                            <p className="text-xs text-slate-600 leading-relaxed whitespace-pre-line">
                              {app.coverNote || "No cover note provided."}
                            </p>
                          </div>

                          {/* Accept Action Button block */}
                          {!viewingBidsJob.isClosed && app.status !== 'Approved' && (
                            <div className="flex justify-end pt-2 border-t border-slate-100">
                              <button
                                onClick={async () => {
                                  if (onAcceptQuotation) {
                                    await onAcceptQuotation(app.id, viewingBidsJob.id);
                                    setViewingBidsJob(null);
                                  } else if (onAcceptQuote) {
                                    await onAcceptQuote(viewingBidsJob.id, app.id);
                                    setViewingBidsJob(null);
                                  }
                                }}
                                className="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold px-4 py-2 rounded-lg transition shadow-sm cursor-pointer"
                              >
                                Accept Quote
                              </button>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>

            <div className="px-6 py-4 bg-slate-50 border-t border-slate-100 flex justify-end text-xs font-semibold">
              <button 
                type="button"
                onClick={() => setViewingBidsJob(null)}
                className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-100 cursor-pointer transition"
              >
                Close Quotes
              </button>
            </div>
          </div>
        </div>
      )}

      {/* MODAL: SOURCING PROPOSALS / QUOTES VIEWER PANEL */}
      {showQuotesModalPost && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-2xl w-full overflow-hidden my-8">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="flex items-center space-x-2">
                <MessageSquare className="w-5 h-5 text-blue-400" />
                <div>
                  <h3 className="font-sans font-bold text-sm sm:text-base">Incoming Sourcing Proposals</h3>
                  <p className="text-[10px] text-slate-400">Review and approve active empty capacity quotations</p>
                </div>
              </div>
              <button 
                onClick={() => setShowQuotesModalPost(null)}
                className="text-slate-400 hover:text-white text-xl cursor-pointer font-bold px-1.5"
              >
                &times;
              </button>
            </div>

            <div className="p-6 space-y-4">
              {/* Order Details & Operational Actions */}
              <div className="bg-slate-50 p-4.5 rounded-xl border border-slate-200 space-y-3">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 border-b border-slate-200 pb-3">
                  <div>
                    <div className="flex items-center space-x-2">
                      <span className="font-mono font-bold text-xs bg-slate-900 text-white px-2 py-0.5 rounded">
                        Order #: {(showQuotesModalPost as any).order_number || showQuotesModalPost.order_number || showQuotesModalPost.id}
                      </span>
                      {(showQuotesModalPost.isProceed || (showQuotesModalPost as any).proceed_status === 'In Progress') && (
                        <span className="bg-emerald-600 text-white font-bold px-2 py-0.5 rounded-full text-[10px] flex items-center space-x-1 shadow-xs">
                          <CheckCircle2 className="w-3 h-3" />
                          <span>Proceed</span>
                        </span>
                      )}
                      {showQuotesModalPost.isClosed && (
                        <span className="bg-emerald-50 text-emerald-700 border border-emerald-200 font-bold px-2 py-0.5 rounded-full text-[10px] flex items-center space-x-1">
                          <Check className="w-3 h-3" />
                          <span>Closed &amp; Agreed</span>
                        </span>
                      )}
                    </div>
                    <h4 className="font-bold text-slate-900 text-sm mt-1.5">{showQuotesModalPost.factoryName}</h4>
                    <p className="text-[11px] text-slate-500">{showQuotesModalPost.factoryLocation || "Bangladesh"}</p>
                  </div>

                  {/* Actions inside order details: Role-based permissions */}
                  {(() => {
                    const isOwner = Boolean(user && showQuotesModalPost.userId === user.id);
                    const hasQuotes = Boolean(showQuotesModalPost.quotes && showQuotesModalPost.quotes.length > 0);

                    if (isOwner) {
                      // 1. For Order Creator: Edit & Delete permitted ONLY UNTIL first quote/proposal is received.
                      if (!hasQuotes) {
                        return (
                          <div className="flex items-center space-x-2 shrink-0">
                            <button
                              type="button"
                              onClick={() => {
                                handleStartEditNeedOrder(showQuotesModalPost);
                                setShowQuotesModalPost(null);
                              }}
                              className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-3 py-1.5 rounded-lg transition flex items-center space-x-1.5 cursor-pointer shadow-xs"
                              title="Edit Need Order Post"
                            >
                              <Pencil className="w-3.5 h-3.5" />
                              <span>Edit</span>
                            </button>
                            <button
                              type="button"
                              onClick={async () => {
                                if (window.confirm("Are you sure you want to delete this capacity post?")) {
                                  await onDeleteNeedOrder(showQuotesModalPost.id);
                                  setShowQuotesModalPost(null);
                                }
                              }}
                              className="bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 text-xs font-bold px-3 py-1.5 rounded-lg transition flex items-center space-x-1.5 cursor-pointer"
                              title="Delete Need Order Post"
                            >
                              <Trash2 className="w-3.5 h-3.5" />
                              <span>Delete</span>
                            </button>
                          </div>
                        );
                      } else {
                        return (
                          <div className="flex items-center space-x-2 shrink-0">
                            <button
                              type="button"
                              disabled
                              className="bg-slate-100 text-slate-400 border border-slate-200 text-xs font-bold px-3 py-1.5 rounded-lg flex items-center space-x-1.5 cursor-not-allowed select-none opacity-60"
                              title="Edit disabled after proposal received"
                            >
                              <Pencil className="w-3.5 h-3.5 text-slate-400" />
                              <span>Edit</span>
                            </button>
                            <button
                              type="button"
                              disabled
                              className="bg-slate-100 text-slate-400 border border-slate-200 text-xs font-bold px-3 py-1.5 rounded-lg flex items-center space-x-1.5 cursor-not-allowed select-none opacity-60"
                              title="Delete disabled after proposal received"
                            >
                              <Trash2 className="w-3.5 h-3.5 text-slate-400" />
                              <span>Delete</span>
                            </button>
                            <div className="flex items-center space-x-1 text-[11px] font-mono font-semibold bg-amber-50 text-amber-800 border border-amber-200 px-2.5 py-1 rounded-lg" title="Order is locked because proposals have been submitted">
                              <Lock className="w-3.5 h-3.5 text-amber-600" />
                              <span>Locked</span>
                            </div>
                          </div>
                        );
                      }
                    } else {
                      // 2. For Other Users (Viewers/Suppliers): No Edit or Delete buttons.
                      // Option to Send Order Proposals directly from the view page.
                      const hasAlreadySent = checkUserHasSentProposal(showQuotesModalPost);
                      const myProposal = showQuotesModalPost.quotes?.find(q => q.userId === user?.id);
                      return (
                        <div className="shrink-0 flex items-center space-x-2">
                          {hasAlreadySent ? (
                            <>
                              <div className="bg-emerald-50 text-emerald-700 border border-emerald-200 text-xs font-bold px-3 py-1.5 rounded-xl flex items-center space-x-1.5 select-none">
                                <CheckCircle className="w-4 h-4 text-emerald-600" />
                                <span>Proposal Already Sent</span>
                              </div>
                              {myProposal && (
                                <button
                                  type="button"
                                  onClick={() => setReviewingProposalQuote(myProposal)}
                                  className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-3 py-1.5 rounded-xl transition flex items-center space-x-1 cursor-pointer"
                                >
                                  <Eye className="w-3.5 h-3.5" />
                                  <span>View My Proposal</span>
                                </button>
                              )}
                            </>
                          ) : (
                            <button
                              type="button"
                              onClick={() => {
                                const targetPost = showQuotesModalPost;
                                setShowQuotesModalPost(null);
                                setShowSubmitQuoteModalPost(targetPost);
                                setQuoteCategory(targetPost.category);
                                setQuoteQuantity(String(targetPost.quantity));
                                setQuoteTargetBudget('');
                                setQuoteStyleName('');
                                setQuoteSmv('');
                                setQuoteSamplePhotos([]);
                                setQuoteSpecDescription('');
                                setQuotePhotoError('');
                              }}
                              className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-4 py-2 rounded-xl shadow-xs transition duration-150 cursor-pointer flex items-center space-x-1.5"
                            >
                              <Send className="w-3.5 h-3.5" />
                              <span>Send Order Proposal</span>
                            </button>
                          )}
                        </div>
                      );
                    }
                  })()}
                </div>

                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
                  <div>
                    <span className="text-[10px] uppercase font-bold text-slate-400 font-mono block">Category / Item</span>
                    <span className="font-bold text-slate-800">
                      {showQuotesModalPost.category}{showQuotesModalPost.garmentItem ? ` / ${showQuotesModalPost.garmentItem}` : ''}
                    </span>
                  </div>
                  <div>
                    <span className="text-[10px] uppercase font-bold text-slate-400 font-mono block">Capacity Quantity</span>
                    <span className="font-mono font-bold text-slate-900">
                      {(showQuotesModalPost.quantity || 0).toLocaleString()} Pcs
                    </span>
                  </div>
                  <div>
                    <span className="text-[10px] uppercase font-bold text-slate-400 font-mono block">Sewing Start Date</span>
                    <span className="font-mono text-slate-700">
                      {showQuotesModalPost.sewingStartDate ? new Date(showQuotesModalPost.sewingStartDate).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : 'N/A'}
                    </span>
                  </div>
                </div>
              </div>

              {/* Incoming Sourcing Proposals: Only visible to Order Creator/Owner or Admin */}
              {user && (showQuotesModalPost.userId === user.id || user.role === 'Admin') && (
                !showQuotesModalPost.quotes || showQuotesModalPost.quotes.length === 0 ? (
                  <div className="p-12 text-center text-slate-500 text-xs">
                    No sourcing proposals received for this capacity slot yet.
                  </div>
                ) : (
                  <div className="overflow-x-auto border border-slate-200 rounded-xl">
                    <table className="w-full text-left border-collapse text-xs">
                      <thead>
                        <tr className="bg-slate-50 text-slate-600 font-mono uppercase tracking-wider text-[10px] border-b border-slate-200">
                          <th className="p-3">Buyer / Company</th>
                          <th className="p-3">Category</th>
                          <th className="p-3">Offered Qty</th>
                          <th className="p-3">Target Budget</th>
                          <th className="p-3 text-center">Action</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-200">
                        {showQuotesModalPost.quotes.map(quote => (
                          <tr key={quote.id} className="hover:bg-slate-50">
                            <td className="p-3 font-semibold text-slate-800">{quote.userName}</td>
                            <td className="p-3">{quote.category}</td>
                            <td className="p-3 font-mono">{(quote.quantity || 0).toLocaleString()} pcs</td>
                            <td className="p-3 font-mono font-medium text-slate-700">৳{(quote.targetBudget || 0).toFixed(2)}</td>
                            <td className="p-3 text-center">
                              <div className="flex items-center justify-center space-x-2">
                                {quote.status === 'Approved' ? (
                                  <span className="bg-emerald-100 text-emerald-800 border border-emerald-200 px-2 py-0.5 rounded-full font-bold text-[9px] uppercase tracking-wider">
                                    Winner
                                  </span>
                                ) : showQuotesModalPost.isClosed ? (
                                  <span className="text-slate-400 font-mono text-[10px] uppercase bg-slate-100 px-2 py-0.5 rounded-full">
                                    Rejected
                                  </span>
                                ) : null}

                                <button
                                  type="button"
                                  onClick={() => setReviewingProposalQuote(quote)}
                                  className="bg-blue-600 hover:bg-blue-700 text-white font-bold px-2.5 py-1 rounded-lg transition duration-150 cursor-pointer text-[10px] flex items-center space-x-1 shadow-xs"
                                  title="View Proposal Details"
                                >
                                  <Eye className="w-3 h-3" />
                                  <span>View</span>
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )
              )}
            </div>
          </div>
        </div>
      )}

      {/* SUB-MODAL: SOURCING PROPOSAL DRILL-DOWN REVIEW PANEL */}
      {reviewingProposalQuote && showQuotesModalPost && (
        <div className="fixed inset-0 bg-slate-900/70 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-lg w-full overflow-hidden my-8">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div>
                <h3 className="font-sans font-bold text-sm sm:text-base">Sourcing Proposal Review</h3>
                <p className="text-[10px] text-slate-400">Review buyer specifications before accepting slot booking</p>
              </div>
              <button 
                type="button"
                onClick={() => {
                  setReviewingProposalQuote(null);
                  const isApprovedOrClosed = Boolean(
                    showQuotesModalPost.isClosed || 
                    showQuotesModalPost.quotes?.some(q => q.status === 'Approved')
                  );
                  if (isApprovedOrClosed || (user && showQuotesModalPost.userId !== user.id && user.role !== 'Admin')) {
                    setShowQuotesModalPost(null);
                  }
                }}
                className="text-slate-400 hover:text-white text-xl cursor-pointer font-bold px-1.5"
              >
                &times;
              </button>
            </div>

            <div className="p-6 space-y-4 text-xs max-h-[80vh] overflow-y-auto">
              {/* Buyer Info Header */}
              <div className="bg-slate-50 border border-slate-200 rounded-xl p-3.5 space-y-1">
                <p className="font-bold text-slate-900 text-sm">{reviewingProposalQuote.userName}</p>
                <p className="text-[10px] text-slate-500 font-mono">Buyer ID: {reviewingProposalQuote.userId}</p>
              </div>

              {/* Metrics Grid */}
              <div className="grid grid-cols-2 gap-3">
                <div className="bg-slate-50 border border-slate-200 rounded-xl p-3">
                  <span className="block text-[10px] uppercase font-bold text-slate-400 font-mono">Offered Quantity</span>
                  <span className="text-sm font-bold font-mono text-slate-900">
                    {reviewingProposalQuote.quantity?.toLocaleString()} Pcs
                  </span>
                </div>
                <div className="bg-slate-50 border border-slate-200 rounded-xl p-3">
                  <span className="block text-[10px] uppercase font-bold text-slate-400 font-mono">Target FOB Price</span>
                  <span className="text-sm font-bold font-mono text-emerald-600">
                    ৳{Number(reviewingProposalQuote.targetBudget || 0).toFixed(2)} / Pc
                  </span>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="bg-slate-50 border border-slate-200 rounded-xl p-3">
                  <span className="block text-[10px] uppercase font-bold text-slate-400 font-mono">Style Name</span>
                  <span className="text-xs font-bold text-slate-900 truncate block">
                    {reviewingProposalQuote.styleName || 'N/A'}
                  </span>
                </div>
                <div className="bg-slate-50 border border-slate-200 rounded-xl p-3">
                  <span className="block text-[10px] uppercase font-bold text-slate-400 font-mono">SMV</span>
                  <span className="text-xs font-bold font-mono text-slate-900">
                    {reviewingProposalQuote.smv ? `${reviewingProposalQuote.smv} mins` : 'N/A'}
                  </span>
                </div>
              </div>

              {/* 4 Sample Photos Gallery */}
              <div className="space-y-1.5">
                <span className="block text-xs font-bold text-slate-700">Sample Photos Gallery</span>
                {reviewingProposalQuote.samplePhotos && reviewingProposalQuote.samplePhotos.length > 0 ? (
                  <div className="grid grid-cols-4 gap-2 pt-1">
                    {reviewingProposalQuote.samplePhotos.map((photo: string, idx: number) => (
                      <div key={idx} className="aspect-square rounded-lg border border-slate-200 overflow-hidden bg-slate-100 shadow-xs">
                        <img src={photo} alt={`Sample ${idx + 1}`} className="w-full h-full object-cover" />
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-[11px] text-slate-400 italic">No sample photos uploaded.</p>
                )}
              </div>

              {/* Detailed Fabric & Spec Description */}
              <div className="space-y-1">
                <span className="block text-xs font-bold text-slate-700">Detailed Fabric &amp; Spec Description</span>
                <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl text-xs font-normal text-slate-700 whitespace-pre-line leading-relaxed">
                  {reviewingProposalQuote.specDescription || 'No detailed specifications provided.'}
                </div>
              </div>

              {/* Relocated Final Operational Action Button at Footer */}
              <div className="pt-4 flex justify-end items-center space-x-2.5 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => {
                    setReviewingProposalQuote(null);
                    const isApprovedOrClosed = Boolean(
                      showQuotesModalPost.isClosed || 
                      showQuotesModalPost.quotes?.some(q => q.status === 'Approved')
                    );
                    if (isApprovedOrClosed || (user && showQuotesModalPost.userId !== user.id && user.role !== 'Admin')) {
                      setShowQuotesModalPost(null);
                    }
                  }}
                  className="bg-white hover:bg-slate-100 text-slate-700 border border-slate-200 font-bold py-2 px-4 rounded-xl cursor-pointer transition"
                >
                  Back
                </button>
                {reviewingProposalQuote.status === 'Approved' ? (
                  <span className="bg-emerald-100 text-emerald-800 px-3 py-2 rounded-xl font-bold text-xs flex items-center space-x-1">
                    <CheckCircle className="w-4 h-4 text-emerald-600" />
                    <span>Already Approved</span>
                  </span>
                ) : (user && (showQuotesModalPost.userId === user.id || user.role === 'Admin')) ? (
                  <button
                    type="button"
                    onClick={async () => {
                      await handleApproveQuote(showQuotesModalPost.id, reviewingProposalQuote.id);
                      setReviewingProposalQuote(null);
                      setShowQuotesModalPost(null);
                    }}
                    className="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 px-5 rounded-xl cursor-pointer shadow-sm transition flex items-center space-x-1.5"
                  >
                    <CheckCircle className="w-4 h-4" />
                    <span>Approve Proposal</span>
                  </button>
                ) : null}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* MODAL: SUBMIT SOURCING PROPOSAL */}
      {showSubmitQuoteModalPost && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-lg w-full overflow-hidden my-8">
            <div className="px-6 py-4 bg-slate-900 text-white flex justify-between items-center">
              <div className="space-y-0.5">
                <h3 className="font-sans font-bold text-sm sm:text-base">Submit Sourcing Proposal</h3>
                <p className="text-[10px] text-slate-400">Offer terms to book capacity with {showSubmitQuoteModalPost.factoryName}</p>
              </div>
              <button 
                type="button"
                onClick={() => setShowSubmitQuoteModalPost(null)}
                className="text-slate-400 hover:text-white text-lg cursor-pointer font-bold px-1.5"
              >
                &times;
              </button>
            </div>

            <form onSubmit={handleSubmitQuote} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
              {/* Static Read-Only Fields for Security Assertion */}
              <div className="space-y-3 bg-slate-50 border border-slate-200 rounded-xl p-4">
                <div className="space-y-1">
                  <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">FACTORY OPERATOR</label>
                  <input
                    type="text"
                    disabled
                    readOnly
                    value={showSubmitQuoteModalPost.factoryName}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 bg-slate-100 text-slate-700 font-bold cursor-not-allowed"
                  />
                </div>
                <div className="space-y-1">
                  <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">CAPABLE GARMENT TYPE</label>
                  <input
                    type="text"
                    disabled
                    readOnly
                    value={`${showSubmitQuoteModalPost.category}${showSubmitQuoteModalPost.garmentItem ? ` / ${showSubmitQuoteModalPost.garmentItem}` : ''}`}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2 bg-slate-100 text-slate-800 font-bold cursor-not-allowed"
                  />
                </div>
              </div>

              {/* Offered Quantity (Pcs) * */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700 font-sans">Offered Quantity (Pcs) *</label>
                <input 
                  type="number"
                  required
                  min={1}
                  placeholder="e.g. 100000"
                  value={quoteQuantity}
                  onChange={(e) => setQuoteQuantity(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono"
                />
              </div>

              {/* Target FOB Price (BDT/Pcs) * */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700 font-sans">Target FOB Price (BDT/Pcs) *</label>
                <div className="relative">
                  <span className="absolute left-3.5 top-2.5 text-slate-500 text-xs sm:text-sm font-bold select-none">৳</span>
                  <input 
                    type="number"
                    step="0.01"
                    min="0.01"
                    required
                    placeholder="e.g. 4.50"
                    value={quoteTargetBudget}
                    onChange={(e) => setQuoteTargetBudget(e.target.value)}
                    className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg pl-8 pr-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono"
                  />
                </div>
              </div>

              {/* Style Name * */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700 font-sans">Style Name *</label>
                <input 
                  type="text"
                  required
                  placeholder="e.g. Vintage Denim Jacket / Style #402"
                  value={quoteStyleName}
                  onChange={(e) => setQuoteStyleName(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-semibold text-slate-800"
                />
              </div>

              {/* SMV * */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700 font-sans">SMV *</label>
                <input 
                  type="number"
                  step="0.01"
                  min="0.1"
                  required
                  placeholder="e.g. 12.50"
                  value={quoteSmv}
                  onChange={(e) => setQuoteSmv(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono"
                />
              </div>

              {/* Sample Photos (Max 4) * */}
              <div className="space-y-1.5">
                <div className="flex justify-between items-center">
                  <label className="block text-xs font-bold text-slate-700 font-sans">Sample Photos (Max 4) *</label>
                  <span className="text-[10px] text-slate-400 font-mono">{quoteSamplePhotos.length}/4 photos uploaded</span>
                </div>
                <input 
                  type="file"
                  multiple
                  accept="image/*"
                  required={quoteSamplePhotos.length === 0}
                  onChange={handleProposalPhotoUpload}
                  className="w-full border border-slate-200 rounded-lg p-2 text-xs text-slate-600 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-xs file:font-bold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer"
                />
                <p className="text-[10px] text-slate-400">Strict limit: Upload up to 4 high-resolution sample product photos.</p>

                {quotePhotoError && (
                  <p className="text-[11px] text-red-600 font-semibold">{quotePhotoError}</p>
                )}

                {quoteSamplePhotos.length > 0 && (
                  <div className="grid grid-cols-4 gap-2 pt-1">
                    {quoteSamplePhotos.map((photo, idx) => (
                      <div key={idx} className="relative group aspect-square rounded-lg border border-slate-200 overflow-hidden bg-slate-100 shadow-xs">
                        <img src={photo} alt={`Sample ${idx + 1}`} className="w-full h-full object-cover" />
                        <button
                          type="button"
                          onClick={() => removeProposalPhoto(idx)}
                          className="absolute top-1 right-1 bg-slate-900/80 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs hover:bg-red-600 transition cursor-pointer"
                        >
                          &times;
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Detailed Fabric & Spec Description * */}
              <div className="space-y-1">
                <label className="block text-xs font-bold text-slate-700 font-sans">Detailed Fabric & Spec Description *</label>
                <textarea 
                  required
                  rows={3}
                  placeholder="e.g. 100% Cotton 12oz Denim, Heavy Enzyme Wash with YKK Zippers, Double Needles Stitching..."
                  value={quoteSpecDescription}
                  onChange={(e) => setQuoteSpecDescription(e.target.value)}
                  className="w-full text-xs sm:text-sm border border-slate-200 rounded-lg px-3.5 py-2.5 focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none"
                />
              </div>

              {showSubmitQuoteModalPost && checkUserHasSentProposal(showSubmitQuoteModalPost) ? (
                <div className="pt-4 border-t border-slate-100 flex items-center justify-between">
                  <div className="text-xs font-bold text-emerald-700 bg-emerald-50 border border-emerald-200 px-3 py-2 rounded-lg flex items-center space-x-1.5 select-none">
                    <CheckCircle className="w-4 h-4 text-emerald-600 shrink-0" />
                    <span>Proposal Already Sent</span>
                  </div>
                  <button 
                    type="button"
                    onClick={() => setShowSubmitQuoteModalPost(null)}
                    className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer text-xs font-semibold"
                  >
                    Close
                  </button>
                </div>
              ) : (
                <div className="pt-4 border-t border-slate-100 flex justify-end space-x-3 text-xs font-semibold">
                  <button 
                    type="button"
                    onClick={() => setShowSubmitQuoteModalPost(null)}
                    className="px-4 py-2.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit"
                    className="px-4 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white shadow-sm flex items-center space-x-1.5 cursor-pointer font-bold"
                  >
                    <Send className="w-3.5 h-3.5" />
                    <span>Send Proposal</span>
                  </button>
                </div>
              )}
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
