'use client'; import { FiAlertTriangle } from 'react-icons/fi'; import { EnterpriseMatch, GraphInsightsPayload, PublicBadgeData, ScoringSummary } from './types'; // import ShareButton from './components/ShareButton'; import AppendixTables from './components/AppendixTables'; import ConnectedPlatforms from './components/ConnectedPlatforms'; import EnterpriseCoaching from './components/EnterpriseCoaching'; import GraphInsights from './components/GraphInsights'; import IpRiskAnalysisDisplay from './components/IpRiskAnalysisDisplay'; import ReportHeader from './components/ReportHeader'; import AiIcon from './components/icons/ai'; import CodeIcon from './components/icons/code'; import RiskIcon from './components/icons/risk'; import { useEffect, useMemo, useState } from 'react'; import ChatWidget from './chat/ChatWidget'; import { matchLabelToColor, yellow } from './colors'; import { BusinessRulesProvider } from './components/BusinessRulesContext'; import CategoryBars from './components/CategoryBars'; import GaugeCard from './components/GaugeCard'; import ResumeView from './components/ResumeView'; import Reveal from './components/Reveal'; import RiskCard from './components/RiskCard'; import RoleOverviewCard from './components/RoleOverviewCard'; import SkillsAppendixTable from './components/SkillsAppendixTable'; import SkillsBubble from './components/SkillsBubble'; import SkillsValidation from './components/SkillsValidation'; import TopContributingFactors from './components/TopContributingFactors'; import UseCases from './components/UseCases'; import { formatLocalDateTime } from './utils/date'; import { getCategoryTooltipCopy } from './utils/provider'; const DEFAULT_AI_CATEGORY_ORDER = [ 'Ecosystems & Providers', 'Orchestration & Dev', 'Specialized AI', 'Machine Learning', 'Infrastructure', 'Governance', ] as const; type ChatWidgetProps = Partial<{ api: string; title: string; hintText: string; loginPath: string; headerOffset: 'auto' | 'none' | number; developerName: string; }>; // const hexToRgba = (hex: string, alpha: number) => { // const clean = hex.replace('#', ''); // const r = parseInt(clean.substring(0, 2), 16); // const g = parseInt(clean.substring(2, 4), 16); // const b = parseInt(clean.substring(4, 6), 16); // return `rgba(${r}, ${g}, ${b}, ${alpha})`; // }; const SharedBadgeDisplay = ({ badgeData, chatProps, headless, selfCheck = false, public: isPublicView = false, suppressChat = false }: { badgeData: PublicBadgeData, chatProps?: ChatWidgetProps, headless?: boolean, selfCheck?: boolean, 'public'?: boolean, suppressChat?: boolean }) => { const { badgeId, developerName, assessmentResult, updatedAt, // connectedAccounts } = badgeData; const { // report_summary, // developer_trust_explanation, screening_sources, // industry_considerations } = assessmentResult; const graphInsights: GraphInsightsPayload = (assessmentResult)?.graph_insights || {} as GraphInsightsPayload; const scoringSummary: ScoringSummary = (assessmentResult)?.scoring_summary || {} as ScoringSummary; const wrapperMaxWidth = 'max-w-5xl'; const isHeadless = !!headless; // Overall and genre scores const overallFinalPercent = Math.round(assessmentResult?.final_percent || 0); // Build category display grouped by genres from scoring_summary.config.genre_mapping const genreMapping = (scoringSummary?.config?.genre_mapping) || {}; const categoryScores = (scoringSummary?.category_scores) || {}; const categoryTopByGraph = (graphInsights?.categoryTopBusiness) || {}; const aiCategoryOrder = graphInsights?.aiCategoryOrder && graphInsights.aiCategoryOrder.length > 0 ? graphInsights.aiCategoryOrder : [...DEFAULT_AI_CATEGORY_ORDER]; const aiCategoryScores = (graphInsights?.aiCategoryScores) || {}; const aiCategoryTopByGraph = (graphInsights?.aiCategoryTopBusiness) || {}; const roleTargets: Record | undefined = (() => { try { const em: EnterpriseMatch | undefined = assessmentResult?.enterprise_match; return (em && em.role && em.role.categoryTargets) ? (em.role.categoryTargets as Record) : undefined; } catch { return undefined; } })(); // const topBusinessForGenre = (genre: string) => { // const cats: string[] = (genreMapping)?.[genre] || []; // const items = []; // for (const c of cats) { // const arr = (categoryTopByGraph)?.[c] || []; // for (const it of arr) items.push(it); // } // items.sort((a, b) => Number(b?.weight || 0) - Number(a?.weight || 0)); // return items.slice(0, 3) as TopBusinessRule[]; // }; // const skillsMatrix = assessmentResult?.skills_matrix || { skills: [] }; const skillsAll = assessmentResult?.skills_all || { skills: [] }; const connected = badgeData?.connectedAccounts || []; // Determine Role Fit & Coaching visibility const hasEnterpriseMatch = !!assessmentResult?.enterprise_match; const hasCoaching = !!(assessmentResult?.enterprise_match?.coaching && Array.isArray(assessmentResult.enterprise_match.coaching.items) && assessmentResult.enterprise_match.coaching.items.length > 0); const hasUseCases = !!(assessmentResult?.enterprise_use_cases?.items && assessmentResult.enterprise_use_cases.items.length > 0); const showRoleFit = hasEnterpriseMatch || hasCoaching || hasUseCases; // Simple tabs for non-headless view const tabs = useMemo(() => { const arr = [ { key: 'overview', label: 'Overview' }, { key: 'technical', label: 'KYD Technical' }, { key: 'risk', label: 'KYD Risk' }, { key: 'ai', label: 'KYD AI' }, { key: 'role', label: showRoleFit ? 'Role Fit & Coaching' : 'Coaching' }, { key: 'resume', label: 'KYD Resume' }, { key: 'appendix', label: 'Appendix' } ]; return arr; }, [showRoleFit]); const [activeTab, setActiveTab] = useState('overview'); useEffect(() => { const handleHashChange = () => { try { const hash = (typeof window !== 'undefined' && window.location.hash ? window.location.hash.substring(1) : '').toLowerCase(); const keys = new Set(tabs.map(t => t.key)); if (hash && keys.has(hash)) setActiveTab(hash); // If the hash targets a skills appendix anchor, switch to Appendix if (hash && (hash.startsWith('appendix-skills') || hash.includes('appendix-skills-cat-') || hash.includes('appendix-connected'))) { setActiveTab('appendix'); } } catch {} }; handleHashChange(); // Run on mount and when tabs change if (typeof window !== 'undefined') { window.addEventListener('hashchange', handleHashChange); return () => { window.removeEventListener('hashchange', handleHashChange); }; } }, [tabs]); const computeStickyTop = (): string | number => { if (isHeadless) return 0; const ho = chatProps?.headerOffset; if (ho === 'none') return 0; if (typeof ho === 'number') return ho; if (ho === 'auto') return 'var(--kyd-tabs-offset, var(--kyd-header-offset, 64px))'; return 'var(--kyd-tabs-offset, 0px)'; }; const TabNav = () => (
{tabs.map(t => { // Map tab key to icon component const IconComp = (() => { if (t.key === 'ai') return AiIcon; if (t.key === 'technical') return CodeIcon; if (t.key === 'risk') return RiskIcon; return null; })(); return ( ); })}
); const AuthenticityNotice = () => { const label = (assessmentResult?.account_authenticity?.label || '').toLowerCase(); if (!label) return null; const isCritical = label === 'likely inauthentic'; const isSuspicious = label === 'suspicious'; if (!isCritical && !isSuspicious) return null; return (
{isCritical ? 'Warning' : 'Attention'}
{assessmentResult?.account_authenticity?.description || (isCritical ? 'We detected signals that some linked accounts may be inauthentic. Review sources below.' : 'Some inconsistencies were observed across linked accounts. Review sources below.')}
{!isPublicView && ( )}
); }; const OverviewSection = () => (
{/* Quadrant layout */}
{/* Top-left: Name, countries, badge image handled by ReportHeader */}
(a?.name || '').toLowerCase())} connectedAccounts={connected} selfCheck={selfCheck} rightBadgeLayout={!hasEnterpriseMatch} />
{/* Top-right: Role match section */} {hasEnterpriseMatch && (
{(() => { const em = assessmentResult?.enterprise_match; if (!em) return null; const role = em.role || {}; return ( ); })()}
)} {/* Bottom-left: Technical score */}
{(() => { const uiTech = graphInsights?.uiSummary?.technical || {}; const techPct = Math.round(Number(uiTech?.percent ?? 0)); const techLabel = uiTech?.label || 'EVIDENCE'; return ( ); })()}
{/* Bottom-right: Risk score */}
{(() => { const uiRisk = graphInsights?.uiSummary?.risk || {}; const riskPctGood = Math.round(Number(uiRisk?.percent_good ?? 0)); const riskLabel = uiRisk?.label || 'RISK'; return ( ); })()}
{/* AI Skills bar chart above Skills Footprint */}
{/* Full-width Skills bubble chart below quadrant */}

Skills Footprint

Report Completed: {formatLocalDateTime(updatedAt)}
); const RoleFitSection = () => { // Local state for expanding long role descriptions const [showFullRoleDescription, setShowFullRoleDescription] = useState(false); const rec = assessmentResult?.recommendations; const recommendationRoleName = (assessmentResult?.enterprise_match?.role?.name || '').trim(); const recommendationsTitle = recommendationRoleName ? `Evidence Recommendations for ${recommendationRoleName}` : 'Evidence Recommendations'; return (
{hasEnterpriseMatch && (
{(() => { const em = assessmentResult?.enterprise_match; if (!em) return null; const role = em.role || {}; const roleName = role?.name || ''; return ( <> Role Alignment{roleName ? ` • ${roleName}` : ''} {(() => { const primaryDescription = (role?.description || em.description || '').trim(); const isLong = primaryDescription.length > 500; const visibleText = isLong && !showFullRoleDescription ? `${primaryDescription.slice(0, 500)}…` : primaryDescription; return (
{roleName}
{primaryDescription ? (
{visibleText} {isLong && ( )}
) : null} {em.description ? (
Alignment Description
-
{em.label}
{em.description}
) : null}
); })()}
); })()}
)} {hasCoaching && (() => { const em = assessmentResult?.enterprise_match; const coaching = em?.coaching; if (!coaching || !(Array.isArray(coaching.items) && coaching.items.length)) return null; return (
Role Alignment Coaching
); })()} {hasUseCases && (
)}
{recommendationsTitle}
{rec?.summary ? (
{rec.summary}
) : null} {Array.isArray(rec?.bullet_points) && (rec?.bullet_points?.length || 0) > 0 ? (
    {rec?.bullet_points?.map((bp, idx) => (
  • {bp}
  • ))}
) : (!rec?.summary ? (
No recommendations available.
) : null)}
); }; const ResumeSection = () => { const resumeJson = (assessmentResult as any)?.resume?.json || null; const roleName = (() => { try { return (assessmentResult?.enterprise_match?.role?.name) || undefined; } catch { return undefined; } })(); return (
); }; const TechnicalSection = () => (
KYD Technical
Top Contributing Factors

KYD Technical - Skills Insights

); const AiSection = () => (
KYD AI
Top Contributing Factors

KYD AI - Skills Insights

); const RiskSection = () => { const adjustedCategoryScores = (() => { if (!badgeData.optOutScreening) return categoryScores; try { const copy = { ...categoryScores } as Record; const key = Object.keys(copy).find(k => /sanctions?.*criminal|sanction|criminal/i.test(k)); if (key) { const prev = copy[key] || {}; const business = { ...(prev.business || {}), percent_progress_signed: 0, percent_progress: 0 }; const combined = { ...(prev.combined || {}), percent_progress_signed: 0, percent_progress: 0 }; copy[key] = { ...prev, business, combined }; } return copy; } catch { return categoryScores; } })(); const getRiskTooltipCopy = (category: string) => { if (badgeData.optOutScreening && /sanction|criminal/i.test(category)) { return 'User opted out of screening; score shown as 0.'; } return getCategoryTooltipCopy(category); }; return (
KYD Risk
Top Contributing Factors
{badgeData.optOutScreening ? (

User Opted Out of Screening

The user chose not to participate in the automated sanctions and risk screening process. The risk score reflects this decision and is for informational purposes only.

) : ( <> {/* Sanctions match cards are temporarily not displayed. The screening data is still generated and stored — this is a display-only suppression. To re-enable, restore: */} )}
); }; const AppendixSection = () => (

Skills

Skills are grouped by evidence: Observed when demonstrated in code, Self-reported when declared by the developer without independent verification, and Certified when confirmed through a credential.
{Array.isArray(graphInsights?.business_rules_all) && graphInsights.business_rules_all.length > 0 && (

Observations

} headless={isHeadless} />
)} {/* Sanctions & Watchlists appendix section is temporarily not displayed. The screening data is still generated and stored — this is a display-only suppression. To re-enable, restore the block below: {!badgeData.optOutScreening && screening_sources && (

Sanctions & Watchlists

{(() => { const ofacProvided = screening_sources.ofac_screen?.sources || []; const lists = [...(screening_sources.ofac_lists || []), ...ofacProvided]; const seen: { [k: string]: boolean } = {}; const dedup: string[] = []; for (let i = 0; i < lists.length; i++) { const val = lists[i]; if (!seen[val]) { seen[val] = true; dedup.push(val); } } const detailed = screening_sources.sanctions_sources_detailed || []; const useDetailed = detailed && detailed.length > 0; return ( ); })()}
)} */}
{/* badge id */}

Badge ID: {badgeId}

© 2025 Know Your Developer, LLC. All rights reserved. KYD Self-Check™, and associated marks are trademarks of Know Your Developer, LLC. This document is confidential, proprietary, and intended solely for the individual or entity to whom it is addressed. Unauthorized use, disclosure, copying, or distribution of this document or any of its contents is strictly prohibited and may be unlawful. Know Your Developer, LLC assumes no responsibility or liability for any errors or omissions contained herein. Report validity subject to the terms and conditions stated on the official Know Your Developer website located at https://knowyourdeveloper.ai.

); return (
{isHeadless ? ( <> {/* Long-form original layout retained for headless/print */} {OverviewSection()} {TechnicalSection()} {RiskSection()} {AiSection()} {AppendixSection()} ) : ( !isPublicView ? ( <>
{activeTab === 'overview' && } {activeTab === 'overview' && OverviewSection()} {activeTab === 'technical' && TechnicalSection()} {activeTab === 'risk' && RiskSection()} {activeTab === 'ai' && AiSection()} {activeTab === 'role' && } {activeTab === 'resume' && } {activeTab === 'appendix' && AppendixSection()}
) : ( <> {OverviewSection()} ) )} {!headless && !suppressChat && ( )}
); }; export default SharedBadgeDisplay;