All files / apps/web/src/backoffice/components JobResultsModal.jsx

0% Statements 0/162
0% Branches 0/203
0% Functions 0/39
0% Lines 0/151

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { useState, useEffect } from 'react'
import { 
  X, Eye, Download, Copy, Brain, Globe, Clock, CheckCircle, 
  AlertCircle, Loader2, ExternalLink, Link2, MapPin, Settings,
  FileText, BarChart3, ListOrdered, AlertTriangle
} from 'lucide-react'
import toast from 'react-hot-toast'
import DataViewerModal from '../../frontoffice/components/DataViewerModal'
 
function JobResultsModal({ isOpen, onClose, job }) {
  const [activeTab, setActiveTab] = useState('outputs')
  const [loading, setLoading] = useState(false)
  const [jobData, setJobData] = useState(null)
  const [crawlResultsOutput, setCrawlResultsOutput] = useState(null)
  const [factsContent, setFactsContent] = useState(null)
  const [showFactsViewer, setShowFactsViewer] = useState(false)
  const [dataContent, setDataContent] = useState(null)
  const [showDataViewer, setShowDataViewer] = useState(false)
  const [extractionContent, setExtractionContent] = useState(null)
  const [showExtractionViewer, setShowExtractionViewer] = useState(false)
  const [screenshotPages, setScreenshotPages] = useState([])
  const [showScreenshotViewer, setShowScreenshotViewer] = useState(false)
 
  const isCrawler = job?.taskQueue === 'crawler-workflows' || job?.sourceType === 'crawler' || job?.sourceType === 'crawl'
 
  useEffect(() => {
    if (isOpen && job?.workflowId) {
      loadResults()
    }
  }, [isOpen, job])
 
  const loadResults = async () => {
    if (!job?.workflowId) return
    setLoading(true)
    try {
      const token = localStorage.getItem('accessToken')
      const response = await fetch(`/api/v1/jobs/${job.workflowId}/results`, {
        headers: token ? { 'Authorization': `Bearer ${token}` } : {}
      })
      const data = await response.json()
      setJobData(data)
    } catch (error) {
      console.error('Error loading results:', error)
      toast.error('Erreur lors du chargement des résultats')
    } finally {
      setLoading(false)
    }
  }
 
  if (!isOpen || !job) return null
 
  const getMinioUrl = (url) => {
    if (!url) return url
    return url.replace('http://minio:9000', 'http://localhost:9000')
  }
 
  const outputs = jobData?.outputs || []
  const input = jobData?.input || null
 
  const handleViewCrawlResults = (output) => {
    setCrawlResultsOutput(output)
  }
 
  const handleViewFacts = async (output) => {
    if (!output?.url) return
    try {
      const response = await fetch(getMinioUrl(output.url))
      const text = await response.text()
      setFactsContent(text)
      setShowFactsViewer(true)
    } catch (err) {
      toast.error('Erreur lors du chargement')
    }
  }
 
  const handleViewData = async (output) => {
    if (!output?.url) return
    try {
      const response = await fetch(getMinioUrl(output.url))
      const text = await response.text()
      setDataContent(text)
      setShowDataViewer(true)
    } catch (err) {
      toast.error('Erreur lors du chargement')
    }
  }
 
  const handleViewExtraction = async (output) => {
    if (!output?.url) return
    try {
      const response = await fetch(getMinioUrl(output.url))
      const text = await response.text()
      setExtractionContent(text)
      setShowExtractionViewer(true)
    } catch (err) {
      toast.error('Erreur lors du chargement')
    }
  }
 
  const handleViewScreenshots = (output) => {
    const pages = output.metadata?.pages || [1]
    const urls = output.url ? [getMinioUrl(output.url)] : []
    setScreenshotPages(urls.map((url, i) => ({ url, page: pages[i] || i + 1 })))
    setShowScreenshotViewer(true)
  }
 
  return (
    <>
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
        <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[85vh] overflow-hidden flex flex-col">
          {/* Header */}
          <div className="flex items-center justify-between p-4 border-b">
            <div className="flex items-center gap-3">
              <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                isCrawler ? 'bg-blue-100' : 'bg-green-100'
              }`}>
                {isCrawler ? (
                  <Globe className="w-5 h-5 text-blue-600" />
                ) : (
                  <Brain className="w-5 h-5 text-green-600" />
                )}
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  {isCrawler ? 'Résultats Crawl' : 'Résultats Workflow'}
                </h3>
                <p className="text-sm text-gray-500 font-mono text-xs">
                  {job.workflowId?.substring(0, 20)}...
                </p>
              </div>
            </div>
            <button 
              onClick={onClose}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X className="w-5 h-5 text-gray-500" />
            </button>
          </div>
 
          {/* Tabs */}
          <div className="flex border-b">
            {job?.status?.toLowerCase() === 'failed' ? (
              <button
                onClick={() => setActiveTab('error')}
                className={`px-6 py-3 text-sm font-medium transition-colors flex items-center gap-2 ${
                  activeTab === 'error'
                    ? 'border-b-2 border-red-500 text-red-600 bg-red-50'
                    : 'text-gray-500 hover:text-gray-700'
                }`}
              >
                <AlertCircle className="w-4 h-4" />
                Erreur
              </button>
            ) : (
              <button
                onClick={() => setActiveTab('outputs')}
                className={`px-6 py-3 text-sm font-medium transition-colors flex items-center gap-2 ${
                  activeTab === 'outputs'
                    ? 'border-b-2 border-indigo-500 text-indigo-600 bg-indigo-50'
                    : 'text-gray-500 hover:text-gray-700'
                }`}
              >
                <FileText className="w-4 h-4" />
                Sorties
              </button>
            )}
            <button
              onClick={() => setActiveTab('parameters')}
              className={`px-6 py-3 text-sm font-medium transition-colors flex items-center gap-2 ${
                activeTab === 'parameters'
                  ? 'border-b-2 border-indigo-500 text-indigo-600 bg-indigo-50'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              <Settings className="w-4 h-4" />
              Paramètres
            </button>
            <button
              onClick={() => setActiveTab('details')}
              className={`px-6 py-3 text-sm font-medium transition-colors flex items-center gap-2 ${
                activeTab === 'details'
                  ? 'border-b-2 border-indigo-500 text-indigo-600 bg-indigo-50'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              <BarChart3 className="w-4 h-4" />
              Détails
            </button>
          </div>
 
          {/* Content */}
          <div className="flex-1 overflow-auto p-6">
            {loading ? (
              <div className="flex items-center justify-center h-32">
                <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
              </div>
            ) : activeTab === 'error' ? (
              <ErrorTab error={jobData?.error} />
            ) : activeTab === 'outputs' ? (
              <OutputsTab 
                outputs={outputs} 
                jobData={jobData}
                getMinioUrl={getMinioUrl} 
                onViewCrawlResults={handleViewCrawlResults}
                onViewFacts={handleViewFacts}
                onViewData={handleViewData}
                onViewExtraction={handleViewExtraction}
                onViewScreenshots={handleViewScreenshots}
              />
            ) : activeTab === 'parameters' ? (
              <ParametersTab input={input} />
            ) : (
              <DetailsTab job={job} jobData={jobData} />
            )}
          </div>
 
          {/* Footer */}
          <div className="p-3 bg-gray-50 border-t text-center text-sm text-gray-500">
            Appuyez sur Echap pour fermer
          </div>
        </div>
      </div>
 
      {/* Crawl Results Viewer Modal */}
      {crawlResultsOutput && jobData && (
        <CrawlResultsViewer jobData={jobData} onClose={() => setCrawlResultsOutput(null)} />
      )}
 
      {/* Facts Viewer Modal */}
      {showFactsViewer && factsContent && (
        <FactsViewerModal content={factsContent} onClose={() => { setShowFactsViewer(false); setFactsContent(null) }} />
      )}
 
      {/* Data Viewer Modal */}
      {showDataViewer && dataContent && (
        <DataViewerModal isOpen={showDataViewer} onClose={() => { setShowDataViewer(false); setDataContent(null) }} content={dataContent} title="Données extraites" />
      )}
 
      {/* Extraction Viewer Modal */}
      {showExtractionViewer && extractionContent && (
        <ExtractionViewerModal content={extractionContent} onClose={() => { setShowExtractionViewer(false); setExtractionContent(null) }} />
      )}
 
      {/* Screenshot Viewer Modal */}
      {showScreenshotViewer && screenshotPages.length > 0 && (
        <ScreenshotViewerModal pages={screenshotPages} onClose={() => { setShowScreenshotViewer(false); setScreenshotPages([]) }} />
      )}
    </>
  )
}
 
function ErrorTab({ error }) {
  if (!error) {
    return (
      <div className="text-center text-gray-500 py-8">
        Aucune erreur disponible
      </div>
    )
  }
 
  return (
    <div className="space-y-4">
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <AlertCircle className="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <h4 className="font-medium text-red-900 mb-2">Erreur du workflow</h4>
            <p className="text-sm text-red-700 whitespace-pre-wrap break-words">{error}</p>
          </div>
        </div>
      </div>
    </div>
  )
}
 
function OutputsTab({ outputs, jobData, getMinioUrl, onViewCrawlResults, onViewFacts, onViewData, onViewExtraction, onViewScreenshots }) {
  if (outputs.length === 0) {
    return (
      <div className="text-center text-gray-500 py-8">
        Aucun résultat disponible
      </div>
    )
  }
 
  const getOutputIcon = (type) => {
    switch (type) {
      case 'facts': return <Brain className="w-5 h-5" />
      case 'crawl-results': return <Globe className="w-5 h-5" />
      case 'extraction': return <FileText className="w-5 h-5" />
      case 'routing': return <MapPin className="w-5 h-5" />
      case 'page-image': return <Globe className="w-5 h-5" />
      default: return <FileText className="w-5 h-5" />
    }
  }
 
  const getOutputColor = (type) => {
    switch (type) {
      case 'facts': return 'bg-purple-100 text-purple-600'
      case 'crawl-results': return 'bg-blue-100 text-blue-600'
      case 'extraction': return 'bg-blue-100 text-blue-600'
      case 'routing': return 'bg-orange-100 text-orange-600'
      case 'page-image': return 'bg-green-100 text-green-600'
      default: return 'bg-gray-100 text-gray-600'
    }
  }
 
  const handleView = (output) => {
    if (output.type === 'crawl-results' && onViewCrawlResults) {
      onViewCrawlResults(output)
    } else if (output.type === 'facts' && onViewFacts) {
      onViewFacts(output)
    } else if (output.type === 'data' && onViewData) {
      onViewData(output)
    } else if (output.type === 'extraction' && onViewExtraction) {
      onViewExtraction(output)
    } else if (output.type === 'page-image' && onViewScreenshots) {
      onViewScreenshots(output)
    }
  }
 
  return (
    <div className="space-y-4">
      {outputs.map((output, index) => (
        <div 
          key={index}
          className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
        >
          <div className="flex items-center gap-3">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${getOutputColor(output.type)}`}>
              {getOutputIcon(output.type)}
            </div>
            <div>
              <div className="font-medium text-gray-900 capitalize">{output.type || 'Output'}</div>
              <div className="text-xs text-gray-500">
                {output.format?.toUpperCase()} • {output.bucket} • {output.metadata?.count ? `${output.metadata.count} items` : ''}
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {output.url && (
              <>
                {(output.type === 'facts' || output.type === 'crawl-results' || output.type === 'data' || output.type === 'extraction' || output.type === 'page-image') && (
                  <button
                    onClick={() => handleView(output)}
                    className="px-3 py-2 text-sm bg-indigo-600 text-white hover:bg-indigo-700 rounded-lg flex items-center gap-1"
                  >
                    <Eye className="w-4 h-4" />
                    Voir
                  </button>
                )}
                <a
                  href={getMinioUrl(output.url)}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                  title="Ouvrir"
                >
                  <ExternalLink className="w-4 h-4 text-gray-600" />
                </a>
                <button
                  onClick={async () => {
                    try {
                      const response = await fetch(getMinioUrl(output.url))
                      const content = await response.text()
                      await navigator.clipboard.writeText(content)
                      toast.success('Copié !')
                    } catch (e) {
                      toast.error('Erreur')
                    }
                  }}
                  className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                  title="Copier"
                >
                  <Copy className="w-4 h-4 text-gray-600" />
                </button>
                <a
                  href={getMinioUrl(output.url)}
                  download
                  className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                  title="Télécharger"
                >
                  <Download className="w-4 h-4 text-gray-600" />
                </a>
              </>
            )}
          </div>
        </div>
      ))}
    </div>
  )
}
 
function ParametersTab({ input }) {
  if (!input) {
    return (
      <div className="text-center text-gray-500 py-8">
        Aucun paramètre disponible
      </div>
    )
  }
 
  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(JSON.stringify(input, null, 2))
      toast.success('JSON copié !')
    } catch (e) {
      toast.error('Erreur')
    }
  }
 
  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <button
          onClick={copyToClipboard}
          className="px-3 py-1.5 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg flex items-center gap-1"
        >
          <Copy className="w-4 h-4" />
          Copier JSON
        </button>
      </div>
      <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm font-mono max-h-[60vh]">
        {JSON.stringify(input, null, 2)}
      </pre>
    </div>
  )
}
 
function DetailsTab({ job, jobData }) {
  const getStatusIcon = (status) => {
    switch (status?.toLowerCase()) {
      case 'completed': return <CheckCircle className="w-5 h-5 text-green-500" />
      case 'failed': return <AlertCircle className="w-5 h-5 text-red-500" />
      case 'running': return <Loader2 className="w-5 h-5 text-yellow-500 animate-spin" />
      default: return <Clock className="w-5 h-5 text-gray-400" />
    }
  }
 
  return (
    <div className="space-y-6">
      {/* Job Info */}
      <div className="bg-gray-50 rounded-lg p-4">
        <h4 className="font-medium text-gray-900 mb-3">Informations du job</h4>
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span className="text-gray-500">Workflow ID:</span>
            <span className="ml-2 font-mono text-xs">{job.workflowId}</span>
          </div>
          <div>
            <span className="text-gray-500">Type:</span>
            <span className="ml-2">{job.type || job.taskQueue}</span>
          </div>
          <div>
            <span className="text-gray-500">Statut:</span>
            <span className="ml-2 flex items-center gap-1">
              {getStatusIcon(job.status)}
              {job.status}
            </span>
          </div>
          <div>
            <span className="text-gray-500">Task Queue:</span>
            <span className="ml-2 font-mono text-xs">{job.taskQueue}</span>
          </div>
          {job.startTime && (
            <div>
              <span className="text-gray-500">Démarré:</span>
              <span className="ml-2">{new Date(job.startTime).toLocaleString()}</span>
            </div>
          )}
          {job.closeTime && (
            <div>
              <span className="text-gray-500">Terminé:</span>
              <span className="ml-2">{new Date(job.closeTime).toLocaleString()}</span>
            </div>
          )}
          {job.runId && (
            <div>
              <span className="text-gray-500">Run ID:</span>
              <span className="ml-2 font-mono text-xs">{job.runId}</span>
            </div>
          )}
        </div>
      </div>
 
      </div>
  )
}
 
function FactsViewerModal({ content, onClose }) {
  let facts = []
  try {
    const parsed = JSON.parse(content)
    facts = parsed.facts || parsed.data || parsed || []
  } catch (e) {
    facts = []
  }
 
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col">
        <div className="flex items-center justify-between p-4 border-b bg-purple-50">
          <div className="flex items-center gap-3">
            <Brain className="w-5 h-5 text-purple-600" />
            <h3 className="text-lg font-semibold text-purple-900">Faits extraits ({facts.length})</h3>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-purple-100 rounded-full transition-colors">
            <X className="w-5 h-5 text-purple-600" />
          </button>
        </div>
        <div className="flex-1 overflow-auto p-4">
          {facts.length === 0 ? (
            <div className="text-center text-gray-500 py-8">
              Aucun fait disponible
            </div>
          ) : (
            <div className="space-y-3">
              {facts.map((fact, index) => {
                const factText = typeof fact === 'string' ? fact : fact.fact || fact.content || fact.text || JSON.stringify(fact)
                const source = fact.source || fact.url || fact.page || null
                const confidence = fact.confidence || fact.score || null
                
                return (
                  <div key={index} className="p-4 bg-purple-50 rounded-lg border-l-4 border-purple-500">
                    <div className="flex items-start justify-between gap-3">
                      <p className="text-gray-800 flex-1">{factText}</p>
                      {confidence && (
                        <span className="px-2 py-1 bg-purple-200 text-purple-800 rounded text-xs font-medium">
                          {Math.round(confidence * 100)}%
                        </span>
                      )}
                    </div>
                    {source && (
                      <div className="mt-2 flex items-center gap-1 text-xs text-gray-500">
                        <Link2 className="w-3 h-3" />
                        <span className="truncate">{source}</span>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          )}
        </div>
        <div className="p-3 bg-purple-50 border-t text-center text-sm text-purple-600">
          {facts.length} fait{facts.length !== 1 ? 's' : ''} extrait{facts.length !== 1 ? 's' : ''}
        </div>
      </div>
    </div>
  )
}
 
function ExtractionViewerModal({ content, onClose }) {
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col">
        <div className="flex items-center justify-between p-4 border-b bg-blue-50">
          <div className="flex items-center gap-3">
            <FileText className="w-5 h-5 text-blue-600" />
            <h3 className="text-lg font-semibold text-blue-900">Extraction</h3>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-blue-100 rounded-full transition-colors">
            <X className="w-5 h-5 text-blue-600" />
          </button>
        </div>
        <div className="flex-1 overflow-auto p-4">
          <pre className="text-sm whitespace-pre-wrap font-mono bg-gray-900 text-gray-100 p-4 rounded-lg max-h-[60vh] overflow-auto">
            {content}
          </pre>
        </div>
      </div>
    </div>
  )
}
 
function ScreenshotViewerModal({ pages, onClose }) {
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] overflow-hidden flex flex-col">
        <div className="flex items-center justify-between p-4 border-b bg-green-50">
          <div className="flex items-center gap-3">
            <Globe className="w-5 h-5 text-green-600" />
            <h3 className="text-lg font-semibold text-green-900">Screenshots ({pages.length})</h3>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-green-100 rounded-full transition-colors">
            <X className="w-5 h-5 text-green-600" />
          </button>
        </div>
        <div className="flex-1 overflow-auto p-4 grid grid-cols-1 md:grid-cols-2 gap-4">
          {pages.map((page, index) => (
            <div key={index} className="border rounded-lg overflow-hidden">
              <img 
                src={page.url} 
                alt={`Page ${page.page}`}
                className="w-full h-auto"
              />
              <div className="p-2 bg-gray-50 text-center text-sm text-gray-600">
                Page {page.page}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
 
function CrawlResultsViewer({ jobData, onClose }) {
  const stats = jobData?.stats || {}
  const facts = stats.factsExtracted || []
  const progress = jobData?.progress || {}
 
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-3xl w-full max-h-[80vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b bg-blue-50">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
              <Globe className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-blue-900">Aperçu du Crawl</h3>
              <p className="text-sm text-blue-600">Statistiques et faits</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-blue-100 rounded-full transition-colors">
            <X className="w-5 h-5 text-blue-600" />
          </button>
        </div>
 
        {/* Content */}
        <div className="flex-1 overflow-auto p-6 space-y-6">
          {/* Stats Grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-gray-50 rounded-lg p-4 text-center">
              <div className="text-3xl font-bold text-gray-900">{stats.pagesCrawled || 0}</div>
              <div className="text-sm text-gray-500">Pages crawllées</div>
            </div>
            <div className="bg-green-50 rounded-lg p-4 text-center">
              <div className="text-3xl font-bold text-green-600">{stats.pagesRelevant || 0}</div>
              <div className="text-sm text-gray-500">Pertinentes</div>
            </div>
            <div className="bg-red-50 rounded-lg p-4 text-center">
              <div className="text-3xl font-bold text-red-600">{stats.pagesFailed || 0}</div>
              <div className="text-sm text-gray-500">Échecs</div>
            </div>
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <div className="text-3xl font-bold text-blue-600">{progress.queueSize || 0}</div>
              <div className="text-sm text-gray-500">Queue restante</div>
            </div>
          </div>
 
          {/* Additional Stats */}
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-medium text-gray-900 mb-3">Détails</h4>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-500">Faits extraits:</span>
                <span className="font-medium">{facts.length}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Synthèses:</span>
                <span className="font-medium">{stats.synthesisTriggered || 0}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Liens découverts:</span>
                <span className="font-medium">{stats.linksQueued || 0}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Router utilisé:</span>
                <span className={`font-medium ${stats.routerUsed ? 'text-green-600' : 'text-gray-400'}`}>
                  {stats.routerUsed ? 'Oui' : 'Non'}
                </span>
              </div>
              {stats.startedAt && (
                <div className="flex justify-between col-span-2">
                  <span className="text-gray-500">Démarré:</span>
                  <span className="font-medium">{new Date(stats.startedAt).toLocaleString()}</span>
                </div>
              )}
              {stats.stopReason && (
                <div className="flex justify-between col-span-2">
                  <span className="text-gray-500">Raison d'arrêt:</span>
                  <span className={`font-medium ${['max_pages_reached', 'queue_empty'].includes(stats.stopReason) ? 'text-green-600' : 'text-red-600'}`}>{stats.stopReason}</span>
                </div>
              )}
            </div>
          </div>
 
          {/* Facts */}
          {facts.length > 0 && (
            <div className="space-y-3">
              <h4 className="font-medium text-gray-900 flex items-center gap-2">
                <Brain className="w-5 h-5 text-purple-600" />
                Faits extraits ({facts.length})
              </h4>
              <div className="space-y-2 max-h-[40vh] overflow-y-auto">
                {facts.map((fact, index) => {
                  const factText = typeof fact === 'string' 
                    ? fact 
                    : fact.fact || fact.content || JSON.stringify(fact)
                  const source = typeof fact === 'object' ? fact.source : null
                  
                  return (
                    <div 
                      key={index}
                      className="p-3 bg-purple-50 rounded-lg border-l-4 border-purple-500"
                    >
                      <p className="text-gray-800 text-sm">{factText}</p>
                      {source && (
                        <div className="mt-1 flex items-center gap-1 text-xs text-gray-500">
                          <Link2 className="w-3 h-3" />
                          <span className="truncate">{source}</span>
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            </div>
          )}
 
          {/* Routing */}
          {stats.routedTo && stats.routedTo.length > 0 && (
            <div className="bg-orange-50 rounded-lg p-4">
              <h4 className="font-medium text-orange-900 mb-3 flex items-center gap-2">
                <MapPin className="w-4 h-4" />
                Routing vers bases de connaissances
              </h4>
              <div className="flex flex-wrap gap-2">
                {stats.routedTo.map((kb, i) => (
                  <span key={i} className="px-3 py-1 bg-orange-100 text-orange-800 rounded-full text-sm font-mono">
                    {kb}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
 
        {/* Footer */}
        <div className="p-3 bg-blue-50 border-t text-center text-sm text-blue-600">
          Appuyez sur Echap pour fermer
        </div>
      </div>
    </div>
  )
}
 
export default JobResultsModal