import { useEffect, useState } from 'react'
import axios from 'axios'
import { X, ExternalLink, Bot, Briefcase, Globe, Users, DollarSign, MapPin, Tag, RefreshCw as RefreshCwIcon, Search as SearchIcon, Pencil, Check, Download, Clock, Lock, Unlock, Calculator, Ruler, Database, Trash2, Flag, AlertTriangle, Scale, Target } from 'lucide-react'
import clsx from 'clsx'
import { ContactsManager, Contact } from './ContactsManager'

interface InspectorProps {
  companyId: number | null
  initialContactId?: number | null
  onClose: () => void
  apiBase: string
}

type Signal = {
  signal_type: string
  confidence: number
  value: string
  proof_text: string
}

type EnrichmentData = {
  source_type: string
  content: any
  is_locked?: boolean
  created_at?: string
}

type IndustryDetails = {
  pains: string | null
  gains: string | null
  priority: string | null
  notes: string | null
  ops_focus_secondary: boolean
}

type CompanyDetail = {
  id: number
  name: string
  website: string | null
  industry_ai: string | null
  status: string
  created_at: string
  signals: Signal[]
  enrichment_data: EnrichmentData[]
  contacts?: Contact[]
  
  // CRM Data (V2)
  crm_name: string | null
  crm_website: string | null
  crm_address: string | null
  crm_vat: string | null
  
  // Quality (V2)
  confidence_score: number | null
  data_mismatch_score: number | null
  
  // Industry Strategy (V2)
  industry_details?: IndustryDetails

  // Marketing AI (V3)
  ai_opener: string | null
  ai_opener_secondary: string | null

  // NEU v0.7.0: Quantitative Metrics
  calculated_metric_name: string | null
  calculated_metric_value: number | null
  calculated_metric_unit: string | null
  standardized_metric_value: number | null
  standardized_metric_unit: string | null
  metric_source: string | null
  metric_source_url: string | null
  metric_proof_text: string | null
  metric_confidence: number | null
  metric_confidence_reason: string | null
}

type ReportedMistake = {
  id: number;
  field_name: string;
  wrong_value: string | null;
  corrected_value: string | null;
  source_url: string | null;
  quote: string | null;
  user_comment: string | null;
  status: 'PENDING' | 'APPROVED' | 'REJECTED';
  created_at: string;
};


export function Inspector({ companyId, initialContactId, onClose, apiBase }: InspectorProps) {
  const [data, setData] = useState<CompanyDetail | null>(null)
  const [loading, setLoading] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)
  const [activeTab, setActiveTab] = useState<'overview' | 'contacts'>('overview')

  const [isReportingMistake, setIsReportingMistake] = useState(false)
  const [existingMistakes, setExistingMistakes] = useState<ReportedMistake[]>([])
  const [reportedFieldName, setReportedFieldName] = useState("")
  const [reportedWrongValue, setReportedWrongValue] = useState("")
  const [reportedCorrectedValue, setReportedCorrectedValue] = useState("")
  const [reportedSourceUrl, setReportedSourceUrl] = useState("")
  const [reportedQuote, setReportedQuote] = useState("")
  const [reportedComment, setReportedComment] = useState("")

  // Polling Logic
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isProcessing) {
      interval = setInterval(() => {
        fetchData(true) // Silent fetch
      }, 2000)
    }
    return () => clearInterval(interval)
  }, [isProcessing, companyId]) 

  useEffect(() => {
    if (initialContactId) {
      setActiveTab('contacts')
    } else {
      setActiveTab('overview')
    }
  }, [initialContactId, companyId])

  const [isEditingWiki, setIsEditingWiki] = useState(false)
  const [wikiUrlInput, setWikiUrlInput] = useState("")
  const [isEditingWebsite, setIsEditingWebsite] = useState(false)
  const [websiteInput, setWebsiteInput] = useState("")
  const [isEditingImpressum, setIsEditingImpressum] = useState(false)
  const [impressumUrlInput, setImpressumUrlInput] = useState("")

  const [industries, setIndustries] = useState<any[]>([])
  const [isEditingIndustry, setIsEditingIndustry] = useState(false)
  const [industryInput, setIndustryInput] = useState("")

  const fetchData = (silent = false) => {
    if (!companyId) return
    if (!silent) setLoading(true)

    const companyRequest = axios.get(`${apiBase}/companies/${companyId}`)
    const mistakesRequest = axios.get(`${apiBase}/mistakes?company_id=${companyId}`)

    Promise.all([companyRequest, mistakesRequest])
      .then(([companyRes, mistakesRes]) => {
        const newData = companyRes.data
        setData(newData)
        setExistingMistakes(mistakesRes.data.items)

        if (isProcessing) {
          const hasWiki = newData.enrichment_data?.some((e: any) => e.source_type === 'wikipedia')
          const hasAnalysis = newData.enrichment_data?.some((e: any) => e.source_type === 'ai_analysis')

          if ((hasWiki && newData.status === 'DISCOVERED') || (hasAnalysis && newData.status === 'ENRICHED')) {
            setIsProcessing(false)
          }
        }
      })
      .catch(console.error)
      .finally(() => { if (!silent) setLoading(false) })
  }

  useEffect(() => {
    fetchData()
    setIsEditingWiki(false)
    setIsEditingWebsite(false)
    setIsEditingImpressum(false)
    setIsEditingIndustry(false)
    setIsProcessing(false) 

    axios.get(`${apiBase}/industries`)
      .then(res => setIndustries(res.data))
      .catch(console.error)
  }, [companyId])

  const handleDiscover = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.post(`${apiBase}/enrich/discover`, { company_id: companyId })
    } catch (e) {
      console.error(e)
      setIsProcessing(false)
    }
  }

  const handleAnalyze = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.post(`${apiBase}/enrich/analyze`, { company_id: companyId })
    } catch (e) {
      console.error(e)
      setIsProcessing(false)
    }
  }

  const handleExport = () => {
    if (!data) return;
    const exportData = {
      metadata: {
        id: data.id,
        exported_at: new Date().toISOString(),
        source: "Company Explorer (Robotics Edition)"
      },
      company: {
        name: data.name,
        website: data.website,
        status: data.status,
        industry_ai: data.industry_ai,
        created_at: data.created_at
      },
      quantitative_potential: {
        calculated_metric_name: data.calculated_metric_name,
        calculated_metric_value: data.calculated_metric_value,
        calculated_metric_unit: data.calculated_metric_unit,
        standardized_metric_value: data.standardized_metric_value,
        standardized_metric_unit: data.standardized_metric_unit,
        metric_source: data.metric_source,
        metric_source_url: data.metric_source_url,
        metric_proof_text: data.metric_proof_text,
        metric_confidence: data.metric_confidence,
        metric_confidence_reason: data.metric_confidence_reason
      },
      enrichment: data.enrichment_data,
      signals: data.signals
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `company-export-${data.id}-${data.name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleWikiOverride = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.post(`${apiBase}/companies/${companyId}/override/wiki?url=${encodeURIComponent(wikiUrlInput)}`)
      setIsEditingWiki(false)
      fetchData()
    } catch (e) {
      alert("Update failed")
      console.error(e)
    } finally {
      setIsProcessing(false)
    }
  }

  const handleWebsiteOverride = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.post(`${apiBase}/companies/${companyId}/override/website?url=${encodeURIComponent(websiteInput)}`)
      setIsEditingWebsite(false)
      fetchData()
    } catch (e) {
      alert("Update failed")
      console.error(e)
    } finally {
      setIsProcessing(false)
    }
  }

  const handleImpressumOverride = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.post(`${apiBase}/companies/${companyId}/override/impressum?url=${encodeURIComponent(impressumUrlInput)}`)
      setIsEditingImpressum(false)
      fetchData()
    } catch (e) {
      alert("Impressum update failed")
      console.error(e)
    } finally {
      setIsProcessing(false)
    }
  }

  const handleIndustryOverride = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.put(`${apiBase}/companies/${companyId}/industry`, { industry_ai: industryInput })
      setIsEditingIndustry(false)
      fetchData()
    } catch (e) {
      alert("Industry update failed")
      console.error(e)
    } finally {
      setIsProcessing(false)
    }
  }

  const handleReevaluateWikipedia = async () => {
    if (!companyId) return
    setIsProcessing(true)
    try {
      await axios.post(`${apiBase}/companies/${companyId}/reevaluate-wikipedia`)
    } catch (e) {
      console.error(e)
      setIsProcessing(false)
    }
  }

  const handleDelete = async () => {
    if (!companyId) return;
    if (!window.confirm(`Are you sure you want to delete "${data?.name}"? This action cannot be undone.`)) {
      return
    }
    try {
      await axios.delete(`${apiBase}/companies/${companyId}`)
      onClose() 
      window.location.reload() 
    } catch (e: any) {
      alert("Failed to delete company: " + (e.response?.data?.detail || e.message))
    }
  }

  const handleLockToggle = async (sourceType: string, currentLockStatus: boolean) => {
    if (!companyId) return
    try {
      await axios.post(`${apiBase}/enrichment/${companyId}/${sourceType}/lock?locked=${!currentLockStatus}`)
      fetchData(true)
    } catch (e) {
      console.error("Lock toggle failed", e)
    }
  }

  interface ReportedMistakeRequest {
    field_name: string;
    wrong_value?: string | null;
    corrected_value?: string | null;
    source_url?: string | null;
    quote?: string | null;
    user_comment?: string | null;
  }

  const handleReportMistake = async () => {
    if (!companyId) return;
    if (!reportedFieldName) {
      alert("Field Name is required.");
      return;
    }

    setIsProcessing(true);
    try {
      const payload: ReportedMistakeRequest = {
        field_name: reportedFieldName,
        wrong_value: reportedWrongValue || null,
        corrected_value: reportedCorrectedValue || null,
        source_url: reportedSourceUrl || null,
        quote: reportedQuote || null,
        user_comment: reportedComment || null,
      };

      await axios.post(`${apiBase}/companies/${companyId}/report-mistake`, payload);
      alert("Mistake reported successfully!");
      setIsReportingMistake(false);
      setReportedFieldName("");
      setReportedWrongValue("");
      setReportedCorrectedValue("");
      setReportedSourceUrl("");
      setReportedQuote("");
      setReportedComment("");
      fetchData(true); 
    } catch (e) {
      alert("Failed to report mistake.");
      console.error(e);
    } finally {
      setIsProcessing(false);
    }
  };

  const handleAddContact = async (contact: Contact) => {
    if (!companyId) return
    try {
      await axios.post(`${apiBase}/contacts`, { ...contact, company_id: companyId })
      fetchData(true)
    } catch (e) {
      alert("Failed to add contact")
      console.error(e)
    }
  }

  const handleEditContact = async (contact: Contact) => {
    if (!contact.id) return
    try {
      await axios.put(`${apiBase}/contacts/${contact.id}`, contact)
      fetchData(true)
    } catch (e) {
      alert("Failed to update contact")
      console.error(e)
    }
  }

  if (!companyId) return null

  const wikiEntry = data?.enrichment_data?.find(e => e.source_type === 'wikipedia')
  const wiki = wikiEntry?.content
  const isLocked = wikiEntry?.is_locked
  const wikiDate = wikiEntry?.created_at

  const aiAnalysisEntry = data?.enrichment_data?.find(e => e.source_type === 'ai_analysis')
  const aiAnalysis = aiAnalysisEntry?.content
  const aiDate = aiAnalysisEntry?.created_at

  const scrapeEntry = data?.enrichment_data?.find(e => e.source_type === 'website_scrape')
  const scrapeData = scrapeEntry?.content
  const impressum = scrapeData?.impressum
  const scrapeDate = scrapeEntry?.created_at

  // Strategy Card Renderer
  const renderStrategyCard = () => {
    if (!data?.industry_details) return null;
    const { pains, gains, priority, notes } = data.industry_details;
    
    return (
      <div className="bg-purple-50 dark:bg-purple-900/10 rounded-xl p-5 border border-purple-100 dark:border-purple-900/50 mb-6">
        <h3 className="text-sm font-semibold text-purple-700 dark:text-purple-300 uppercase tracking-wider mb-3 flex items-center gap-2">
          <Target className="h-4 w-4" /> Strategic Fit (Notion)
        </h3>
        
        <div className="grid gap-4">
           <div className="flex items-center gap-2">
              <span className="text-xs text-slate-500 font-bold uppercase">Status:</span>
              <span className={clsx("px-2 py-0.5 rounded text-xs font-bold", 
                  priority === "Freigegeben" ? "bg-green-100 text-green-700" : "bg-yellow-100 text-yellow-700"
              )}>{priority || "N/A"}</span>
           </div>

           {pains && (
             <div>
               <div className="text-[10px] text-red-600 dark:text-red-400 uppercase font-bold tracking-tight mb-1">Pain Points</div>
               <div className="text-sm text-slate-700 dark:text-slate-300 whitespace-pre-line">{pains}</div>
             </div>
           )}
           
           {gains && (
             <div>
               <div className="text-[10px] text-green-600 dark:text-green-400 uppercase font-bold tracking-tight mb-1">Gain Points</div>
               <div className="text-sm text-slate-700 dark:text-slate-300 whitespace-pre-line">{gains}</div>
             </div>
           )}
           
           {notes && (
             <div className="pt-2 border-t border-purple-200 dark:border-purple-800">
                <div className="text-[10px] text-purple-500 uppercase font-bold tracking-tight">Internal Notes</div>
                <div className="text-xs text-slate-500 italic">{notes}</div>
             </div>
           )}
        </div>
      </div>
    )
  }

  // Marketing AI Card Renderer
  const renderMarketingCard = () => {
    if (!data?.ai_opener && !data?.ai_opener_secondary) return null;
    
    return (
      <div className="bg-orange-50 dark:bg-orange-900/10 rounded-xl p-5 border border-orange-100 dark:border-orange-900/50 mb-6">
        <h3 className="text-sm font-semibold text-orange-700 dark:text-orange-300 uppercase tracking-wider mb-3 flex items-center gap-2">
          <Bot className="h-4 w-4" /> Marketing AI (Openers)
        </h3>
        
        <div className="space-y-4">
           {data.ai_opener && (
             <div className="p-3 bg-white dark:bg-slate-900 rounded border border-orange-200 dark:border-orange-800">
               <div className="flex justify-between items-center mb-1">
                 <div className="text-[10px] text-orange-600 dark:text-orange-400 uppercase font-bold tracking-tight">Primary: Infrastructure/Cleaning</div>
               </div>
               <div className="text-sm text-slate-700 dark:text-slate-200 leading-relaxed italic">"{data.ai_opener}"</div>
             </div>
           )}
           
           {data.ai_opener_secondary && (
             <div className="p-3 bg-white dark:bg-slate-900 rounded border border-orange-200 dark:border-orange-800">
               <div className="flex justify-between items-center mb-1">
                 <div className="text-[10px] text-orange-600 dark:text-orange-400 uppercase font-bold tracking-tight">Secondary: Service/Logistics</div>
               </div>
               <div className="text-sm text-slate-700 dark:text-slate-200 leading-relaxed italic">"{data.ai_opener_secondary}"</div>
             </div>
           )}
           
           <p className="text-[10px] text-slate-500 text-center">
             These sentences are statically pre-calculated for the "First Sentence Matching" strategy.
           </p>
        </div>
      </div>
    )
  }

  // CRM Comparison and Data Quality Renderer
  const renderDataQualityCard = () => {
    if (!data) return null;
    const hasCrmData = data.crm_name || data.crm_website;
    const hasQualityScores = data.confidence_score != null || data.data_mismatch_score != null;

    if (!hasCrmData && !hasQualityScores) return null;
    
    const confidenceScore = data.confidence_score ?? 0;
    const mismatchScore = data.data_mismatch_score ?? 0;

    const getConfidenceColor = (score: number) => {
        if (score > 0.8) return { bg: "bg-green-100", text: "text-green-700" };
        if (score > 0.5) return { bg: "bg-yellow-100", text: "text-yellow-700" };
        return { bg: "bg-red-100", text: "text-red-700" };
    }
    
    const getMismatchColor = (score: number) => {
        if (score <= 0.3) return { bg: "bg-green-100", text: "text-green-700" };
        if (score <= 0.5) return { bg: "bg-yellow-100", text: "text-yellow-700" };
        return { bg: "bg-red-100", text: "text-red-700" };
    }

    const confidenceColors = getConfidenceColor(confidenceScore);
    const mismatchColors = getMismatchColor(mismatchScore);

    return (
      <div className="bg-slate-50 dark:bg-slate-950 rounded-lg p-4 border border-slate-200 dark:border-slate-800 mb-6">
         <div className="flex justify-between items-center mb-4">
            <h3 className="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">
              <Scale className="h-4 w-4" /> Data Quality & CRM Sync
            </h3>
         </div>
         
         <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs mb-4">
            {/* AI Quality Metrics */}
            <div className="space-y-3 p-3 bg-white dark:bg-slate-900 rounded border border-slate-200 dark:border-slate-800">
                <div className="text-[10px] font-bold text-slate-400 uppercase">AI Quality Scores</div>
                {data.confidence_score != null && (
                    <div className="flex items-center justify-between">
                        <span className="text-slate-500 dark:text-slate-400">Classification Confidence</span>
                        <span className={clsx("font-bold px-2 py-0.5 rounded text-xs", confidenceColors.bg, confidenceColors.text)}>
                            {(confidenceScore * 100).toFixed(0)}%
                        </span>
                    </div>
                )}
                {data.data_mismatch_score != null && (
                     <div className="flex items-center justify-between">
                        <span className="text-slate-500 dark:text-slate-400">CRM Data Match</span>
                        <span className={clsx("font-bold px-2 py-0.5 rounded text-xs", mismatchColors.bg, mismatchColors.text)}>
                            {((1 - mismatchScore) * 100).toFixed(0)}%
                        </span>
                    </div>
                )}
            </div>
             
             {/* CRM Data Display */}
             <div className="p-3 bg-slate-100 dark:bg-slate-800/50 rounded">
                <div className="text-[10px] font-bold text-slate-400 uppercase mb-2">SuperOffice (CRM)</div>
                <div className="space-y-2">
                    <div><span className="text-slate-400">Name:</span> <span className="font-medium break-all">{data.crm_name || "-"}</span></div>
                    <div><span className="text-slate-400">Web:</span> <span className="font-mono break-all">{data.crm_website || "-"}</span></div>
                </div>
            </div>
         </div>
         
         <div className="text-xs">
            <div className="p-3 bg-white dark:bg-slate-900 rounded border border-blue-100 dark:border-blue-900/50">
                <div className="text-[10px] font-bold text-blue-500 uppercase mb-2">Enriched Data (AI)</div>
                <div className="space-y-2">
                    <div><span className="text-slate-400">Name:</span> <span className="font-medium text-slate-900 dark:text-white">{data.name}</span></div>
                    <div><span className="text-slate-400">Web:</span> <span className="font-mono text-blue-600 dark:text-blue-400">{data.website}</span></div>
                </div>
            </div>
         </div>
      </div>
    )
  }

  return (
    <div className="fixed inset-y-0 right-0 w-full md:w-[600px] bg-white dark:bg-slate-900 border-l border-slate-200 dark:border-slate-800 shadow-2xl transform transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
      {loading ? (
        <div className="p-8 text-slate-500">Loading details...</div>
      ) : !data ? (
        <div className="p-8 text-red-400">Failed to load data.</div>
      ) : (
        <div className="flex flex-col h-full">
          {/* Header */}
          <div className="p-6 border-b border-slate-200 dark:border-slate-800 bg-slate-50/80 dark:bg-slate-950/50 backdrop-blur-sm sticky top-0 z-10">
            <div className="flex justify-between items-start mb-4">
              <h2 className="text-xl font-bold text-slate-900 dark:text-white leading-tight">{data.name}</h2>
              <div className="flex items-center gap-2">
                <button
                  onClick={handleDelete}
                  className="p-1.5 text-slate-500 hover:text-red-600 dark:hover:text-red-500 transition-colors"
                  title="Delete Company"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
                <button
                  onClick={handleExport}
                  className="p-1.5 text-slate-500 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                  title="Export JSON"
                >
                  <Download className="h-4 w-4" />
                </button>
                <button
                  onClick={() => setIsReportingMistake(true)}
                  className="p-1.5 text-slate-500 hover:text-orange-600 dark:hover:text-orange-500 transition-colors"
                  title="Report a Mistake"
                >
                  <Flag className="h-4 w-4" />
                </button>
                <button
                  onClick={() => fetchData(true)}
                  className="p-1.5 text-slate-500 hover:text-slate-900 dark:hover:text-white transition-colors"
                  title="Refresh"
                >
                  <RefreshCwIcon className={clsx("h-4 w-4", (loading || isProcessing) && "animate-spin")} />
                </button>
                <button onClick={onClose} className="p-1.5 text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors">
                  <X className="h-6 w-6" />
                </button>
              </div>
            </div>

            <div className="flex flex-wrap gap-2 text-sm items-center">
              {!isEditingWebsite ? (
                <div className="flex items-center gap-2 group">
                  {data.website && data.website !== "k.A." ? (
                    <a
                      href={data.website.startsWith('http') ? data.website : `https://${data.website}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-1 text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 transition-colors font-medium"
                    >
                      <Globe className="h-3.5 w-3.5" /> {new URL(data.website.startsWith('http') ? data.website : `https://${data.website}`).hostname.replace('www.', '')}
                    </a>
                  ) : (
                    <span className="text-slate-500 italic text-xs">No website</span>
                  )}
                  <button
                    onClick={() => { setWebsiteInput(data.website && data.website !== "k.A." ? data.website : ""); setIsEditingWebsite(true); }}
                    className="p-1 text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors opacity-0 group-hover:opacity-100"
                    title="Edit Website URL"
                  >
                    <Pencil className="h-3 w-3" />
                  </button>
                </div>
              ) : (
                <div className="flex items-center gap-1 animate-in fade-in zoom-in duration-200">
                  <input
                    type="text"
                    value={websiteInput}
                    onChange={e => setWebsiteInput(e.target.value)}
                    placeholder="https://..."
                    className="bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-700 rounded px-2 py-0.5 text-[10px] text-slate-900 dark:text-white focus:ring-1 focus:ring-blue-500 outline-none w-48"
                    autoFocus
                  />
                  <button
                    onClick={handleWebsiteOverride}
                    className="p-1 bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-400 rounded hover:bg-green-200 dark:hover:bg-green-900 transition-colors"
                  >
                    <Check className="h-3 w-3" />
                  </button>
                  <button
                    onClick={() => setIsEditingWebsite(false)}
                    className="p-1 text-slate-500 hover:text-red-500 transition-colors"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </div>
              )}
            </div>

            {existingMistakes.length > 0 && (
              <div className="mt-4 p-4 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800/50 rounded-lg">
                <h4 className="flex items-center gap-2 text-sm font-bold text-orange-800 dark:text-orange-300 mb-3">
                  <AlertTriangle className="h-4 w-4" />
                  Existing Correction Proposals
                </h4>
                <div className="space-y-3 max-h-40 overflow-y-auto pr-2">
                  {existingMistakes.map(mistake => (
                    <div key={mistake.id} className="text-xs p-3 bg-white dark:bg-slate-800/50 rounded border border-slate-200 dark:border-slate-700/50">
                      <div className="flex justify-between items-start">
                        <span className="font-bold text-slate-800 dark:text-slate-200">{mistake.field_name}</span>
                         <span className={clsx("px-2 py-0.5 rounded-full text-[9px] font-medium", {
                          'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-300': mistake.status === 'PENDING',
                          'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300': mistake.status === 'APPROVED',
                           'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-300': mistake.status === 'REJECTED'
                        })}>
                          {mistake.status}
                        </span>
                      </div>
                      <p className="text-slate-600 dark:text-slate-400 mt-1">
                        <span className="line-through text-red-500/80">{mistake.wrong_value || 'N/A'}</span> → <strong className="text-green-600 dark:text-green-400">{mistake.corrected_value || 'N/A'}</strong>
                      </p>
                      {mistake.user_comment && <p className="mt-2 text-slate-500 italic">"{mistake.user_comment}"</p>}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Mistake Report Form (Missing in previous version) */}
            {isReportingMistake && (
                <div className="mt-4 p-4 bg-slate-100 dark:bg-slate-800 rounded border border-slate-200 dark:border-slate-700 animate-in slide-in-from-top-2">
                    <h4 className="text-sm font-bold mb-3 flex justify-between items-center">
                        Report a Data Error
                        <button onClick={() => setIsReportingMistake(false)} className="text-slate-400 hover:text-red-500"><X className="h-4 w-4"/></button>
                    </h4>
                    <div className="space-y-3">
                        <div>
                            <label className="block text-[10px] uppercase font-bold text-slate-500 mb-1">Field Name (Required)</label>
                            <input className="w-full text-xs p-2 rounded border dark:bg-slate-900 dark:border-slate-700" value={reportedFieldName} onChange={e => setReportedFieldName(e.target.value)} placeholder="e.g. Revenue, Employee Count" />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <div>
                                <label className="block text-[10px] uppercase font-bold text-slate-500 mb-1">Wrong Value</label>
                                <input className="w-full text-xs p-2 rounded border dark:bg-slate-900 dark:border-slate-700" value={reportedWrongValue} onChange={e => setReportedWrongValue(e.target.value)} />
                            </div>
                            <div>
                                <label className="block text-[10px] uppercase font-bold text-slate-500 mb-1">Correct Value</label>
                                <input className="w-full text-xs p-2 rounded border dark:bg-slate-900 dark:border-slate-700" value={reportedCorrectedValue} onChange={e => setReportedCorrectedValue(e.target.value)} />
                            </div>
                        </div>
                        <div>
                            <label className="block text-[10px] uppercase font-bold text-slate-500 mb-1">Source URL / Proof</label>
                            <input className="w-full text-xs p-2 rounded border dark:bg-slate-900 dark:border-slate-700" value={reportedSourceUrl} onChange={e => setReportedSourceUrl(e.target.value)} />
                        </div>
                        <div>
                            <label className="block text-[10px] uppercase font-bold text-slate-500 mb-1">Comment</label>
                            <textarea className="w-full text-xs p-2 rounded border dark:bg-slate-900 dark:border-slate-700" rows={2} value={reportedComment} onChange={e => setReportedComment(e.target.value)} />
                        </div>
                        <button 
                            onClick={handleReportMistake}
                            disabled={isProcessing}
                            className="w-full bg-orange-600 hover:bg-orange-700 text-white py-2 rounded text-xs font-bold"
                        >
                            SUBMIT REPORT
                        </button>
                    </div>
                </div>
            )}

            <div className="mt-6 flex border-b border-slate-200 dark:border-slate-800">
              <button
                onClick={() => setActiveTab('overview')}
                className={clsx(
                  "px-4 py-2 text-sm font-medium transition-colors border-b-2",
                  activeTab === 'overview'
                    ? "border-blue-500 text-blue-600 dark:text-blue-400"
                    : "border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200"
                )}
              >
                Overview
              </button>
              <button
                onClick={() => setActiveTab('contacts')}
                className={clsx(
                  "px-4 py-2 text-sm font-medium transition-colors border-b-2 flex items-center gap-2",
                  activeTab === 'contacts'
                    ? "border-blue-500 text-blue-600 dark:text-blue-400"
                    : "border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200"
                )}
              >
                Contacts
                {data.contacts && data.contacts.length > 0 && (
                  <span className="bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-300 px-1.5 py-0.5 rounded-full text-[10px] min-w-[1.25rem] text-center">
                    {data.contacts.length}
                  </span>
                )}
              </button>
            </div>
          </div>

          <div className="p-6 space-y-8 bg-white dark:bg-slate-900">

            {activeTab === 'overview' && (
              <>
                <div className="flex gap-2 mb-6">
                  <button
                    onClick={handleDiscover}
                    disabled={isProcessing}
                    className="flex-1 flex items-center justify-center gap-2 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 disabled:opacity-50 text-slate-700 dark:text-white text-xs font-bold py-2 rounded-md border border-slate-200 dark:border-slate-700 transition-all shadow-sm"
                  >
                    <SearchIcon className="h-3.5 w-3.5" />
                    {isProcessing ? "Processing..." : "DISCOVER"}
                  </button>
                  <button
                    onClick={handleAnalyze}
                    disabled={isProcessing || !data.website || data.website === 'k.A.'}
                    className="flex-1 flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white text-xs font-bold py-2 rounded-md transition-all shadow-lg shadow-blue-900/20"
                  >
                    <Bot className="h-3.5 w-3.5" />
                    {isProcessing ? "Analyzing..." : "ANALYZE POTENTIAL"}
                  </button>
                </div>

                {renderDataQualityCard()}
                {renderStrategyCard()}
                {renderMarketingCard()}

                <div className="bg-slate-50 dark:bg-slate-950 rounded-lg p-4 border border-slate-200 dark:border-slate-800 flex flex-col gap-2">
                  <div className="flex items-center justify-between mb-1">
                    <div className="flex items-center gap-2">
                      <div className="p-1 bg-white dark:bg-slate-800 rounded text-slate-400">
                        <Briefcase className="h-3 w-3" />
                      </div>
                      <span className="text-[10px] uppercase font-bold text-slate-500 tracking-wider">Official Legal Data</span>
                    </div>
                    <div className="flex items-center gap-2">
                      {scrapeDate && (
                        <div className="text-[10px] text-slate-500 flex items-center gap-1">
                          <Clock className="h-3 w-3" /> {new Date(scrapeDate).toLocaleDateString()}
                        </div>
                      )}

                      {scrapeEntry && (
                        <button
                          onClick={() => handleLockToggle('website_scrape', scrapeEntry.is_locked || false)}
                          className={clsx(
                            "p-1 rounded transition-colors",
                            scrapeEntry.is_locked
                              ? "text-green-600 dark:text-green-400 hover:text-green-700"
                              : "text-slate-400 hover:text-slate-900 dark:hover:text-white"
                          )}
                          title={scrapeEntry.is_locked ? "Data Locked" : "Unlocked"}
                        >
                          {scrapeEntry.is_locked ? <Lock className="h-3.5 w-3.5" /> : <Unlock className="h-3.5 w-3.5" />}
                        </button>
                      )}

                      {!isEditingImpressum ? (
                        <button
                          onClick={() => { setImpressumUrlInput(""); setIsEditingImpressum(true); }}
                          className="p-1 text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors"
                          title="Set Impressum URL Manually"
                        >
                          <Pencil className="h-3 w-3" />
                        </button>
                      ) : (<div className="flex items-center gap-1 animate-in fade-in zoom-in duration-200">
                        <button
                          onClick={handleImpressumOverride}
                          className="p-1 bg-green-100 dark:bg-green-900/50 text-green-600 dark:text-green-400 rounded hover:bg-green-200 dark:hover:bg-green-900 transition-colors"
                        >
                          <Check className="h-3 w-3" />
                        </button>
                        <button
                          onClick={() => setIsEditingImpressum(false)}
                          className="p-1 text-slate-500 hover:text-red-500 transition-colors"
                        >
                          <X className="h-3 w-3" />
                        </button>
                      </div>
                      )}
                    </div>
                  </div>

                  {isEditingImpressum && (
                    <div className="mb-2 animate-in slide-in-from-top-1 duration-200">
                      <input
                        type="text"
                        value={impressumUrlInput}
                        onChange={e => setImpressumUrlInput(e.target.value)}
                        placeholder="https://.../impressum"
                        className="w-full bg-white dark:bg-slate-900 border border-slate-300 dark:border-slate-700 rounded px-2 py-1 text-xs text-slate-900 dark:text-white focus:ring-1 focus:ring-blue-500 outline-none"
                        autoFocus
                      />
                    </div>
                  )}

                  {impressum ? (
                    <>
                      <div className="text-sm font-medium text-slate-900 dark:text-white">
                        {impressum.legal_name || "Unknown Legal Name"}
                      </div>

                      <div className="flex items-start gap-2 text-xs text-slate-500 dark:text-slate-400">
                        <MapPin className="h-3 w-3 mt-0.5 shrink-0" />
                        <div>
                          <div>{impressum.street}</div>
                          <div>{impressum.zip} {impressum.city}</div>
                        </div>
                      </div>

                      {(impressum.email || impressum.phone) && (
                        <div className="mt-2 pt-2 border-t border-slate-200 dark:border-slate-900 flex flex-wrap gap-4 text-[10px] text-slate-500 font-mono">
                          {impressum.email && <span>{impressum.email}</span>}
                          {impressum.phone && <span>{impressum.phone}</span>}
                          {impressum.vat_id && <span className="text-blue-600 dark:text-blue-400/80">VAT: {impressum.vat_id}</span>}
                        </div>
                      )}
                    </>
                  ) : !isEditingImpressum && (
                    <div className="text-[10px] text-slate-500 italic py-2">
                      No legal data found. Click pencil to provide direct Impressum link.
                    </div>
                  )}
                </div>

                <div className="bg-blue-50/50 dark:bg-blue-900/10 rounded-xl p-5 border border-blue-100 dark:border-blue-900/50 mb-6">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <div className="text-[10px] text-blue-600 dark:text-blue-400 uppercase font-bold tracking-tight mb-2">Industry Focus</div>
                      {!isEditingIndustry ? (
                        <div className="flex items-center gap-3">
                          <div className="p-2 bg-white dark:bg-slate-800 rounded-lg shadow-sm">
                            <Briefcase className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                          </div>
                          <div>
                            <div className="text-sm font-semibold text-slate-900 dark:text-white">{data.industry_ai || "Not Classified"}</div>
                            <button
                              onClick={() => { setIndustryInput(data.industry_ai || "Others"); setIsEditingIndustry(true); }}
                              className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                            >
                              Change Industry & Re-Extract
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div className="space-y-2">
                          <select
                            value={industryInput}
                            onChange={e => setIndustryInput(e.target.value)}
                            className="w-full bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-700 rounded px-2 py-1.5 text-sm text-slate-900 dark:text-white focus:ring-1 focus:ring-blue-500 outline-none"
                            autoFocus
                          >
                            <option value="Others">Others</option>
                            {industries.map(ind => (
                              <option key={ind.id} value={ind.name}>{ind.name}</option>
                            ))}
                          </select>
                          <div className="flex gap-2">
                            <button
                              onClick={handleIndustryOverride}
                              className="flex-1 px-3 py-1.5 bg-blue-600 text-white rounded text-xs font-medium hover:bg-blue-700 transition-colors flex items-center justify-center gap-2"
                            >
                              <Check className="h-3.5 w-3.5" /> Save & Re-Extract
                            </button>
                            <button
                              onClick={() => setIsEditingIndustry(false)}
                              className="px-3 py-1.5 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 rounded text-xs font-medium hover:bg-slate-300 dark:hover:bg-slate-600 transition-colors"
                            >
                              <X className="h-3.5 w-3.5" />
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                    <div>
                      <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight mb-2">Analysis Status</div>
                      <div className="flex items-center gap-3">
                        <div className="p-2 bg-white dark:bg-slate-800 rounded-lg shadow-sm">
                          <Bot className="h-5 w-5 text-slate-500" />
                        </div>
                        <div className={clsx(
                          "px-3 py-1 rounded-full text-xs font-bold",
                          data.status === 'ENRICHED' ? "bg-green-100 text-green-700 border border-green-200" :
                            data.status === 'DISCOVERED' ? "bg-blue-100 text-blue-700 border border-blue-200" :
                              "bg-slate-100 text-slate-600 border border-slate-200"
                        )}>
                          {data.status}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {aiAnalysis && (
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">
                        <Bot className="h-4 w-4" /> AI Strategic Dossier
                      </h3>
                      {aiDate && (
                        <div className="text-[10px] text-slate-500 flex items-center gap-1">
                          <Clock className="h-3 w-3" /> {new Date(aiDate).toLocaleDateString()}
                        </div>
                      )}
                    </div>
                    <div className="bg-white dark:bg-slate-800/30 rounded-xl p-5 border border-slate-200 dark:border-slate-800/50 space-y-4 shadow-sm">
                      <div>
                        <div className="text-[10px] text-blue-600 dark:text-blue-400 uppercase font-bold tracking-tight mb-1">Business Model</div>
                        <p className="text-sm text-slate-700 dark:text-slate-200 leading-relaxed">{aiAnalysis.business_model || "No summary available."}</p>
                      </div>
                      {aiAnalysis.infrastructure_evidence && (
                        <div className="pt-4 border-t border-slate-200 dark:border-slate-800/50">
                          <div className="text-[10px] text-orange-600 dark:text-orange-400 uppercase font-bold tracking-tight mb-1">Infrastructure Evidence</div>
                          <p className="text-sm text-slate-600 dark:text-slate-300 italic leading-relaxed">"{aiAnalysis.infrastructure_evidence}"</p>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <h3 className="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">
                      <Globe className="h-4 w-4" /> Company Profile (Wikipedia)
                    </h3>

                    <div className="flex items-center gap-2">
                      {wikiDate && (
                        <div className="text-[10px] text-slate-500 flex items-center gap-1 mr-2">
                          <Clock className="h-3 w-3" /> {new Date(wikiDate).toLocaleDateString()}
                        </div>
                      )}

                      {wikiEntry && (
                        <button
                          onClick={() => handleLockToggle('wikipedia', wikiEntry.is_locked || false)}
                          className={clsx(
                            "p-1 rounded transition-colors mr-1",
                            wikiEntry.is_locked
                              ? "text-green-600 dark:text-green-400 hover:text-green-700"
                              : "text-slate-400 hover:text-slate-900 dark:hover:text-white"
                          )}
                          title={wikiEntry.is_locked ? "Wiki Data Locked" : "Wiki Data Unlocked"}
                        >
                          {wikiEntry.is_locked ? <Lock className="h-3.5 w-3.5" /> : <Unlock className="h-3.5 w-3.5" />}
                        </button>
                      )}

                      <button
                        onClick={handleReevaluateWikipedia}
                        disabled={isProcessing}
                        className="p-1 text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors disabled:opacity-50"
                        title="Re-run metric extraction from Wikipedia text"
                      >
                        <RefreshCwIcon className={clsx("h-3.5 w-3.5", isProcessing && "animate-spin")} />
                      </button>

                      {!isEditingWiki ? (
                        <button
                          onClick={() => { setWikiUrlInput(wiki?.url || ""); setIsEditingWiki(true); }}
                          className="p-1 text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                          title="Edit / Override URL"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </button>
                      ) : (<div className="flex items-center gap-1">
                        <button
                          onClick={handleWikiOverride}
                          className="p-1 bg-green-100 dark:bg-green-900/50 text-green-600 dark:text-green-400 rounded hover:bg-green-200 dark:hover:bg-green-900 transition-colors"
                          title="Save & Rescan"
                        >
                          <Check className="h-3.5 w-3.5" />
                        </button>
                        <button
                          onClick={() => setIsEditingWiki(false)}
                          className="p-1 text-slate-500 hover:text-red-500 transition-colors"
                          title="Cancel"
                        >
                          <X className="h-3.5 w-3.5" />
                        </button>
                      </div>
                      )}
                    </div>
                  </div>

                  {isEditingWiki && (
                    <div className="mb-2">
                      <input
                        type="text"
                        value={wikiUrlInput}
                        onChange={e => setWikiUrlInput(e.target.value)}
                        placeholder="Paste Wikipedia URL here..."
                        className="w-full bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-700 rounded px-2 py-1 text-sm text-slate-900 dark:text-white focus:ring-1 focus:ring-blue-500 outline-none"
                      />
                      <p className="text-[10px] text-slate-500 mt-1">Paste a valid URL. Saving will trigger a re-scan.</p>
                    </div>
                  )}

                  {wiki && wiki.url !== 'k.A.' && !isEditingWiki ? (
                    <div>
                      <div className="bg-white dark:bg-slate-800/30 rounded-xl p-5 border border-slate-200 dark:border-slate-800/50 relative overflow-hidden shadow-sm">
                        <div className="absolute top-0 right-0 p-3 opacity-10">
                          <Globe className="h-16 w-16 text-slate-900 dark:text-white" />
                        </div>

                        {isLocked && (
                          <div className="absolute top-2 right-2 flex items-center gap-1 px-1.5 py-0.5 bg-yellow-100 dark:bg-yellow-900/30 border border-yellow-200 dark:border-yellow-800/50 rounded text-[9px] text-yellow-600 dark:text-yellow-500">
                            <Tag className="h-2.5 w-2.5" /> Manual Override
                          </div>
                        )}

                        <p className="text-sm text-slate-600 dark:text-slate-300 leading-relaxed italic mb-4">
                          "{wiki.first_paragraph}"
                        </p>

                        <div className="grid grid-cols-2 gap-y-4 gap-x-6">
                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg text-blue-500">
                              <Users className="h-4 w-4" />
                            </div>
                            <div>
                              <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight">Employees</div>
                              <div className="text-sm text-slate-700 dark:text-slate-200 font-medium">{wiki.mitarbeiter || 'k.A.'}</div>
                            </div>
                          </div>

                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg text-green-500">
                              <DollarSign className="h-4 w-4" />
                            </div>
                            <div>
                              <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight">Revenue</div>
                              <div className="text-sm text-slate-700 dark:text-slate-200 font-medium">{wiki.umsatz && wiki.umsatz !== 'k.A.' ? `${wiki.umsatz} Mio. €` : 'k.A.'}</div>
                            </div>
                          </div>

                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg text-orange-500">
                              <MapPin className="h-4 w-4" />
                            </div>
                            <div>
                              <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight">Headquarters</div>
                              <div className="text-sm text-slate-700 dark:text-slate-200 font-medium">{wiki.sitz_stadt}{wiki.sitz_land ? `, ${wiki.sitz_land}` : ''}</div>
                            </div>
                          </div>

                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg text-purple-500">
                              <Briefcase className="h-4 w-4" />
                            </div>
                            <div>
                              <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight">Wiki Industry</div>
                              <div className="text-sm text-slate-700 dark:text-slate-200 font-medium truncate max-w-[150px]" title={wiki.branche}>{wiki.branche || 'k.A.'}</div>
                            </div>
                          </div>
                        </div>

                        {wiki.categories && wiki.categories !== 'k.A.' && (
                          <div className="mt-6 pt-5 border-t border-slate-200 dark:border-slate-800/50">
                            <div className="flex items-start gap-2 text-xs text-slate-500 mb-2">
                              <Tag className="h-3 w-3 mt-0.5" /> Categories
                            </div>
                            <div className="flex flex-wrap gap-1.5">
                              {wiki.categories.split(',').map((cat: string) => (
                                <span key={cat} className="px-2 py-0.5 bg-slate-100 dark:bg-slate-900 text-slate-600 dark:text-slate-400 rounded-full text-[10px] border border-slate-200 dark:border-slate-800">
                                  {cat.trim()}
                                </span>
                              ))}
                            </div>
                          </div>
                        )}

                        <div className="mt-4 flex justify-end">
                          <a href={wiki.url} target="_blank" className="text-[10px] text-blue-600 dark:text-blue-500 hover:text-blue-500 dark:hover:text-blue-400 flex items-center gap-1 font-bold">
                            WIKIPEDIA <ExternalLink className="h-2.5 w-2.5" />
                          </a>
                        </div>
                      </div>
                    </div>
                  ) : !isEditingWiki ? (
                    <div className="p-4 rounded-xl border border-dashed border-slate-200 dark:border-slate-800 text-center text-slate-500 dark:text-slate-600">
                      <Globe className="h-5 w-5 mx-auto mb-2 opacity-20" />
                      <p className="text-xs">No Wikipedia profile found yet.</p>
                    </div>
                  ) : null}
                </div>

                <div>
                  <h3 className="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3 flex items-center gap-2">
                    <Bot className="h-4 w-4" /> Quantitative Potential
                  </h3>

                  {data.calculated_metric_value != null || data.standardized_metric_value != null ? (
                    <div className="bg-slate-50 dark:bg-slate-950 rounded-lg p-4 border border-slate-200 dark:border-slate-800 space-y-4">
                      {data.calculated_metric_value != null && (
                        <div className="flex items-start gap-3">
                          <div className="p-2 bg-white dark:bg-slate-800 rounded-lg text-blue-500 mt-1">
                            <Calculator className="h-4 w-4" />
                          </div>
                          <div>
                            <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight">{data.calculated_metric_name || 'Calculated Metric'}</div>
                            <div className="text-xl text-slate-900 dark:text-white font-bold">
                              {data.calculated_metric_value.toLocaleString('de-DE')}
                              <span className="text-sm font-medium text-slate-500 ml-1">{data.calculated_metric_unit}</span>
                            </div>
                          </div>
                        </div>
                      )}

                      {data.standardized_metric_value != null && (
                        <div className="flex items-start gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
                          <div className="p-2 bg-white dark:bg-slate-800 rounded-lg text-green-500 mt-1">
                            <Ruler className="h-4 w-4" />
                          </div>
                          <div>
                            <div className="text-[10px] text-slate-500 uppercase font-bold tracking-tight">Standardized Potential ({data.standardized_metric_unit})</div>
                            <div className="text-xl text-green-600 dark:text-green-400 font-bold">
                              {data.standardized_metric_value.toLocaleString('de-DE')}
                              <span className="text-sm font-medium text-slate-500 ml-1">{data.standardized_metric_unit}</span>
                            </div>
                            <p className="text-xs text-slate-500 mt-1">Comparable value for potential analysis.</p>
                          </div>
                        </div>
                      )}

                      {data.metric_source && (
                        <div className="flex justify-between items-center text-[10px] text-slate-500 pt-2 border-t border-slate-200 dark:border-slate-800">
                          
                          {data.metric_confidence != null && (
                            <div className="flex items-center gap-1.5" title={data.metric_confidence_reason || "No reason provided"}>
                               <span className="uppercase font-bold tracking-tight text-[9px]">Confidence:</span>
                               <div className="flex items-center gap-1">
                                  <div className={clsx("h-2 w-2 rounded-full", 
                                      data.metric_confidence >= 0.8 ? "bg-green-500" : 
                                      data.metric_confidence >= 0.5 ? "bg-yellow-500" : "bg-red-500")} />
                                  <span className={clsx("font-medium",
                                      data.metric_confidence >= 0.8 ? "text-green-700 dark:text-green-400" : 
                                      data.metric_confidence >= 0.5 ? "text-yellow-700 dark:text-yellow-400" : "text-red-700 dark:text-red-400"
                                  )}>
                                    {(data.metric_confidence * 100).toFixed(0)}%
                                  </span>
                               </div>
                            </div>
                          )}

                          <div className="flex items-center gap-1">
                            <Database className="h-3 w-3" />
                            <span>Source:</span>
                            <span 
                              title={data.metric_proof_text || "No proof text available"} 
                              className="font-medium text-slate-600 dark:text-slate-400 capitalize cursor-help border-b border-dotted border-slate-400"
                            >
                               {data.metric_source}
                            </span>
                            {data.metric_source_url && (
                              <a href={data.metric_source_url} target="_blank" rel="noopener noreferrer" className="ml-1 text-blue-600 dark:text-blue-400 hover:underline">
                                <ExternalLink className="h-3 w-3 inline" />
                              </a>
                            )}
                          </div>
                        </div>
                      )}

                    </div>
                  ) : (
                    <div className="p-4 rounded-xl border border-dashed border-slate-200 dark:border-slate-800 text-center text-slate-500 dark:text-slate-600">
                      <Bot className="h-5 w-5 mx-auto mb-2 opacity-20" />
                      <p className="text-xs">No quantitative data calculated yet.</p>
                      <p className="text-xs mt-1">Run "Analyze Potential" to extract metrics.</p>
                    </div>
                  )}
                </div>
              </>
            )}
            
            {activeTab === 'contacts' && (
                <ContactsManager 
                    contacts={data.contacts} 
                    initialContactId={initialContactId}
                    onAddContact={handleAddContact} 
                    onEditContact={handleEditContact} 
                />
            )}
          </div>
        </div>
      )}
    </div>
  )
}
