const { useState, useRef, useEffect } = React;

// ─── Brand ───────────────────────────────────────────────────────────────────
const C = {
  bg:      "#07090F", sbg: "#0B0E18", card: "#0F1626", card2: "#141D30",
  border:  "#1A2540", border2: "#223060",
  teal: "#12CFC0", violet: "#7B5CF6", amber: "#F59E0B",
  emerald: "#34D399", coral: "#F87171", cyan: "#22D3EE", blue: "#3B82F6",
  white: "#FFFFFF", off: "#7A90B0", dim: "#2E4060",
};
const FF = "'Helvetica Neue', Arial, sans-serif";

// ─── Data ────────────────────────────────────────────────────────────────────
const PEER_SCORE = 3.24;
const PEERS = [
  { name:"P&G", score:3.71, c:C.emerald },
  { name:"Unilever", score:3.44, c:C.teal },
  { name:"Coca-Cola NA", score:3.24, c:C.amber, you:true },
  { name:"Pepsi", score:3.02, c:C.off },
  { name:"AB InBev", score:2.83, c:C.dim },
];

const FUNCTIONS = [
  {
    id:"content", label:"Content & Creative AI", icon:"✦", score:3.82, color:C.violet,
    status:"Advanced", tools:7, gapCount:2, roi:"$12.4M",
    goals:["Generate campaign creative at 10× speed of traditional production","Personalize assets across 50+ markets simultaneously","Reduce agency dependency for tier-2 content by 40%","Maintain brand consistency through AI-governed guardrails"],
    sources:[{n:"Azure OpenAI (GPT-4o)",t:"GenAI platform",s:"Live"},{n:"Adobe Firefly API",t:"Creative AI",s:"Live"},{n:"Create Real Magic",t:"Internal GenAI",s:"Live"},{n:"Canva Enterprise AI",t:"Design automation",s:"Scaling"},{n:"Persado",t:"Language optimization",s:"Pilot"},{n:"Runway ML",t:"Video generation",s:"Evaluating"}],
    findings:[
      {sev:"high", text:"Content AI governance framework missing — 7 GenAI tools in production with no unified policy for brand safety, copyright, or model versioning.", value:"$8M"},
      {sev:"medium", text:"Create Real Magic platform showing 3.8× engagement lift but measurement methodology is inconsistent across markets.", value:"$3.2M"},
      {sev:"low", text:"AI content approval workflow adds 2.3 days vs 0.4 days for AI-native approval — eliminating the speed advantage of GenAI.", value:"$1.2M"},
    ],
    advisories:[
      {
        title:"Unified Content AI Governance Framework",
        priority:"P1", timeline:"60 days", annualValue:"$8M", investment:"$420K",
        finding:"7 GenAI tools in production with no unified brand safety policy, copyright framework, or model versioning — each team operating under different informal rules.",
        advisory:"Build a lightweight Content AI CoE (2-3 people) with three deliverables: (1) a single-page AI Content Policy covering brand voice, copyright, and approval gates; (2) a model versioning and rollback protocol; (3) a centralized AI performance dashboard connecting all 7 tools.",
        whyNow:"Competitors including Pepsi and P&G have already launched internal AI content policies following high-profile brand safety incidents in 2025. The regulatory window for voluntary self-governance closes in Q3 2026 with new EU AI Act content provisions.",
        disruption:"Generative AI content governance is the #1 priority for FMCG CMOs globally in 2026. Companies without a governance layer face brand safety incidents averaging $12M in brand value erosion (Gartner 2026).",
        roadmap:["Appoint Content AI CoE lead from existing brand operations team (Week 1)","Audit all 7 tools for current brand guidelines compliance (Weeks 2-3)","Draft and ratify AI Content Policy with legal and brand teams (Weeks 3-5)","Build model versioning protocol and deploy to all active tools (Weeks 5-8)","Launch centralized performance dashboard with weekly reporting (Week 9-12)"],
        tools:[
          {n:"Writer.com", cat:"Content Governance", desc:"Brand-governed GenAI platform with real-time style guide enforcement and content policy guardrails.", why:"Enforces CCNA brand voice rules across all 7 GenAI tools through a centralized policy layer — eliminating per-tool inconsistency.", deploy:"SaaS", fit:"High", cost:"$80K–$120K/yr"},
          {n:"Jasper AI", cat:"Content Operations", desc:"Enterprise AI content platform with workflow automation, brand voice controls, and multi-team collaboration.", why:"Provides the approval workflow automation that cuts CCNA's 2.3-day content review cycle to under 4 hours.", deploy:"SaaS", fit:"High", cost:"$60K–$90K/yr"},
          {n:"Copyleaks", cat:"Copyright & IP", desc:"AI-powered copyright detection and content provenance verification at enterprise scale.", why:"Scans all AI-generated content before publication — closes the copyright gap in CCNA's current 7-tool stack.", deploy:"API", fit:"Medium", cost:"$18K–$30K/yr"},
          {n:"Truepic", cat:"Content Authenticity", desc:"Content authenticity and AI provenance tracking using cryptographic verification.", why:"Provides audit trail for AI-generated content — required for regulatory compliance under 2026 EU AI Act provisions.", deploy:"SaaS", fit:"Medium", cost:"$24K–$40K/yr"},
        ],
        benefits:{speed:38, risk:42, quality:12, cost:8},
      },
    ],
  },
  {
    id:"insights", label:"Consumer Insights AI", icon:"◎", score:3.61, color:C.teal,
    status:"Advanced", tools:5, gapCount:2, roi:"$9.8M",
    goals:["Real-time consumer sentiment across 180+ markets","Predictive demand signals 8-12 weeks ahead","Replace 60% of qual research with AI-synthesized insight","Connect signals directly to innovation pipeline"],
    sources:[{n:"Sprinklr AI",t:"Social intelligence",s:"Live"},{n:"Qualtrics XM AI",t:"Experience data",s:"Live"},{n:"Nielsen AI Predict",t:"Market intelligence",s:"Live"},{n:"Tastewise",t:"Food & bev trend AI",s:"Pilot"},{n:"Brandwatch",t:"Social listening",s:"Live"}],
    findings:[
      {sev:"high", text:"Consumer insight AI outputs not connected to campaign planning — insight-to-activation cycle is 6-8 weeks; competitors operating at 2 weeks.", value:"$6.2M"},
      {sev:"medium", text:"Five separate insight AI platforms with no unified layer — each brand team accessing different data, creating contradictory consumer narratives.", value:"$2.8M"},
      {sev:"low", text:"Tastewise pilot showing 78% trend prediction accuracy but not scaled beyond innovation team.", value:"$0.8M"},
    ],
    advisories:[
      {
        title:"Consumer Intelligence Unification Hub",
        priority:"P1", timeline:"90 days", annualValue:"$6.2M", investment:"$680K",
        finding:"Insight-to-activation cycle is 6-8 weeks while competitors operate at 2 weeks. Five AI platforms producing contradictory data with no unified consumer narrative.",
        advisory:"Build a Consumer Intelligence Hub — a single aggregation layer that pulls from all 5 platforms into one weekly insight brief. This is a workflow/integration project, not a new tool purchase. Estimated 90-day build using existing tech stack.",
        whyNow:"Pepsi launched a unified consumer intelligence platform in Q1 2026. P&G's CMO cited real-time insight capability as their #1 competitive advantage in Q4 2025 earnings. Every week of delay = 1 week of competitive disadvantage in campaign relevance.",
        disruption:"McKinsey data shows FMCG companies with sub-2-week insight cycles see 14% higher campaign ROI and 22% better new product success rates. The gap between leaders and laggards is widening monthly.",
        roadmap:["Map all 5 platform APIs and data schemas (Week 1-2)","Design unified consumer insight taxonomy and data model (Week 2-3)","Build aggregation pipeline connecting all 5 platforms (Week 3-6)","Create automated weekly insight brief template (Week 6-8)","Train brand teams on new unified workflow (Week 8-10)","Launch live dashboard with campaign team integration (Week 10-12)"],
        tools:[
          {n:"Databricks", cat:"Data Platform", desc:"Unified data lakehouse that connects all 5 CCNA insight platforms into a single analytics environment with real-time streaming.", why:"Aggregates Sprinklr, Qualtrics, Nielsen, Tastewise, and Brandwatch into one data model — the core of the Consumer Intelligence Hub.", deploy:"Cloud", fit:"High", cost:"$180K–$320K/yr"},
          {n:"ThoughtSpot", cat:"AI Analytics", desc:"AI-powered self-serve analytics with natural language querying for non-technical marketing users.", why:"Enables CCNA brand teams to query the unified insight layer without data science support — cutting insight cycle from 6 weeks to 2 weeks.", deploy:"SaaS", fit:"High", cost:"$120K–$200K/yr"},
          {n:"Snowflake", cat:"Data Federation", desc:"Cloud data platform enabling cross-platform data sharing without copying or moving raw data.", why:"Federates Nielsen, Sprinklr, and Brandwatch data without violating each platform's data residency terms.", deploy:"Cloud", fit:"Medium", cost:"$90K–$160K/yr"},
          {n:"Tableau Pulse", cat:"Insight Distribution", desc:"AI-curated insight digest that proactively surfaces relevant consumer signals to stakeholders.", why:"Delivers the weekly unified insight brief to CMO and brand leads without requiring them to log into any platform.", deploy:"SaaS", fit:"Medium", cost:"$48K–$80K/yr"},
        ],
        benefits:{speed:55, quality:28, cost:12, risk:5},
      },
    ],
  },
  {
    id:"personalization", label:"Personalization at Scale", icon:"◈", score:3.02, color:C.amber,
    status:"Opportunity Gap", tools:4, gapCount:3, roi:"$14.2M",
    goals:["Deliver 1:1 journeys across digital, DTC, and loyalty","Reduce mass broadcast spend by 20%","Increase loyalty engagement through AI-personalized rewards","Connect retail to individual preferences at point of purchase"],
    sources:[{n:"Salesforce Marketing Cloud AI",t:"Journey automation",s:"Live"},{n:"Adobe Experience Platform",t:"Real-time CDP",s:"Scaling"},{n:"Dynamic Yield",t:"Web personalization",s:"Live"},{n:"Optimizely AI",t:"Experimentation",s:"Pilot"}],
    findings:[
      {sev:"high", text:"Adobe Experience Platform deployed but only 22% of consumer profiles unified — personalization engine has insufficient data to operate effectively.", value:"$8.8M"},
      {sev:"high", text:"Loyalty program AI operating independently from campaign personalization — missed opportunity to use loyalty behavior in real-time targeting.", value:"$4.2M"},
      {sev:"medium", text:"Dynamic Yield showing 18% conversion lift on web but learnings not applied to email, push, or in-store channels.", value:"$1.2M"},
    ],
    advisories:[
      {
        title:"Customer Profile Unification Sprint",
        priority:"P1", timeline:"120 days", annualValue:"$8.8M", investment:"$1.2M",
        finding:"AEP is deployed but only 22% of consumer profiles are unified. The personalization engine is running on incomplete data, limiting effectiveness to a fraction of its potential.",
        advisory:"Execute a focused Customer Data Unification Sprint: (1) prioritize the top 40% of consumers by value for immediate unification, (2) build identity resolution bridges between Salesforce, AEP, and loyalty databases, (3) implement consent-compliant data collection to fill profile gaps.",
        whyNow:"AEP licenses are being paid for regardless — this is a utilization problem, not a tech problem. Every month at 22% profile coverage is ~$730K in unrealized personalization ROI sitting on already-purchased infrastructure.",
        disruption:"P&G achieved 85% consumer profile unification by Q2 2025, enabling their 'Always-On Personalization' program that contributed to 3.2% market share gain in personal care. Coca-Cola NA is 18 months behind the industry leader.",
        roadmap:["Audit current identity resolution gaps in AEP (Week 1-2)","Map all consumer data sources and connection status (Week 2-3)","Build priority consumer cohort (top 40% by LTV) as pilot (Week 3-6)","Deploy identity bridges between AEP, Salesforce, and loyalty DB (Week 4-10)","Validate personalization quality improvement with A/B test (Week 10-14)","Scale to full consumer base (Week 14-18)"],
        tools:[
          {n:"LiveRamp", cat:"Identity Resolution", desc:"Privacy-safe identity resolution connecting online and offline consumer identifiers across channels and devices.", why:"Resolves CCNA's fragmented consumer identifiers across AEP, Salesforce, loyalty, and retail — the core enabler of the 22%→80% profile unification target.", deploy:"SaaS", fit:"High", cost:"$150K–$250K/yr"},
          {n:"Adobe Real-Time CDP", cat:"Customer Data Platform", desc:"Real-time customer data platform with AI-powered profile unification and instant segmentation activation.", why:"Already licensed — needs configuration to enable real-time identity bridging. Fully utilizing existing AEP investment before new purchases.", deploy:"Cloud", fit:"High", cost:"$200K–$400K/yr"},
          {n:"Acxiom", cat:"Data Enrichment", desc:"Consumer data enrichment with 3,000+ attributes covering demographics, behavior, and purchase intent.", why:"Fills profile gaps for consumers where CCNA has partial data — accelerates path to 80% profile completeness.", deploy:"API", fit:"Medium", cost:"$80K–$140K/yr"},
          {n:"mParticle", cat:"Data Pipeline", desc:"Real-time customer data pipeline connecting data sources to downstream activation platforms.", why:"Streams loyalty events to Salesforce Marketing Cloud in real-time — enabling the loyalty-to-campaign trigger automation.", deploy:"SaaS", fit:"Medium", cost:"$90K–$150K/yr"},
        ],
        benefits:{revenue:52, loyalty:28, efficiency:14, risk:6},
      },
      {
        title:"Loyalty-Campaign Data Bridge",
        priority:"P1", timeline:"60 days", annualValue:"$4.2M", investment:"$380K",
        finding:"Loyalty program (55M+ members) and marketing campaign system operate as completely separate data environments with no real-time data sharing.",
        advisory:"Build a real-time API bridge between the loyalty platform and Salesforce Marketing Cloud to enable: (1) loyalty behavior signals to trigger personalized campaign actions, (2) campaign engagement to update loyalty recommendations, (3) unified customer view for marketing and loyalty teams.",
        whyNow:"Coca-Cola's loyalty program has 55M+ members — one of the most valuable first-party data assets in FMCG — but it's invisible to the campaign personalization engine. This is the single highest-leverage, lowest-cost AI activation opportunity in the portfolio.",
        disruption:"Starbucks' Deep Brew loyalty-marketing integration is the benchmark — $700M in incremental revenue attributed to AI-personalized loyalty-to-campaign bridging in 2025.",
        roadmap:["API design between loyalty platform and Salesforce MC (Week 1-2)","Build real-time event streaming for loyalty signals (Week 2-4)","Deploy first 5 loyalty-triggered campaign automations (Week 4-6)","A/B test vs control group (Week 6-8)","Scale to full loyalty segment automation (Week 8-10)"],
        tools:[
          {n:"MuleSoft", cat:"Integration Platform", desc:"Enterprise-grade API integration platform for real-time event streaming between loyalty and marketing systems.", why:"Builds the loyalty-to-Salesforce MC API bridge that enables real-time behavior triggers without replacing either platform.", deploy:"Cloud", fit:"High", cost:"$160K–$280K/yr"},
          {n:"Braze", cat:"Campaign Activation", desc:"Real-time customer engagement platform with loyalty signal ingestion and instant campaign activation.", why:"Alternative to Salesforce MC for loyalty-triggered micro-campaigns — processes loyalty events in under 50ms for true real-time activation.", deploy:"SaaS", fit:"High", cost:"$120K–$220K/yr"},
          {n:"Segment", cat:"Event Streaming", desc:"Customer data pipeline with real-time event streaming and identity resolution.", why:"Streams loyalty events (earn, redeem, tier change) to campaign and personalization platforms simultaneously.", deploy:"SaaS", fit:"Medium", cost:"$80K–$140K/yr"},
        ],
        benefits:{revenue:60, retention:25, efficiency:10, cost:5},
      },
    ],
  },
  {
    id:"media", label:"Media Optimization AI", icon:"⬡", score:2.84, color:C.cyan,
    status:"Opportunity Gap", tools:4, gapCount:4, roi:"$8.6M",
    goals:["Shift 25% of buying to AI-optimized programmatic by Q4","Real-time budget reallocation based on performance","Reduce wasted spend by 15% through precision targeting","Connect creative performance back to content AI"],
    sources:[{n:"The Trade Desk AI",t:"Programmatic buying",s:"Live"},{n:"Google DV360 AI",t:"Display & video",s:"Live"},{n:"Aperiam MTA",t:"Attribution modeling",s:"Pilot"},{n:"Sightly AI",t:"Moment marketing",s:"Evaluating"}],
    findings:[
      {sev:"high", text:"Attribution model is last-click across 60% of media — AI optimization engines making decisions on deeply flawed attribution data.", value:"$5.2M"},
      {sev:"high", text:"Trade Desk and DV360 operating as separate environments with no unified optimization layer — budget arbitrage opportunity missed.", value:"$2.4M"},
      {sev:"medium", text:"Real-time budget reallocation exists in tools but 48-hour approval workflows eliminate the real-time advantage.", value:"$0.7M"},
    ],
    advisories:[
      {
        title:"Multi-Touch Attribution Model Migration",
        priority:"P1", timeline:"90 days", annualValue:"$5.2M", investment:"$920K",
        finding:"60% of media spend is being optimized using last-click attribution — a methodology known to systematically over-credit lower-funnel touchpoints and under-invest in brand-building channels.",
        advisory:"Migrate to a data-driven multi-touch attribution (MTA) model using a hybrid ML approach: (1) deploy probabilistic MTA for digital channels, (2) integrate offline sales data for MTA calibration, (3) build attribution dashboard connecting MTA outputs to media buying algorithms in Trade Desk and DV360.",
        whyNow:"Last-click attribution is causing estimated $5.2M annual misallocation. With Q3 2026 campaign planning beginning in 60 days, fixing attribution now means next campaign cycle benefits from accurate data from day one.",
        disruption:"Unilever migrated to AI-powered MTA in 2024 and reported 18% improvement in media efficiency within 6 months. P&G has used data-driven attribution since 2022 — they are 4 years ahead.",
        roadmap:["Audit current attribution touchpoints and data completeness (Week 1-2)","Select and configure MTA model (probabilistic + deterministic hybrid) (Week 2-4)","Integrate offline sales signals for model training (Week 3-6)","Validate MTA model against historical conversions (Week 6-8)","Connect MTA outputs to Trade Desk and DV360 bid optimization (Week 8-10)","Launch Attribution Dashboard for media teams (Week 10-12)"],
        tools:[
          {n:"Neustar (TransUnion)", cat:"Media Measurement", desc:"AI-powered multi-touch attribution with offline sales integration and cross-channel measurement normalization.", why:"Replaces last-click with probabilistic MTA across CCNA's digital ecosystem — directly feeds corrected attribution data into Trade Desk and DV360 bidding algorithms.", deploy:"SaaS", fit:"High", cost:"$200K–$350K/yr"},
          {n:"Rockerbox", cat:"Unified Measurement", desc:"Unified MTA + Marketing Mix Modeling (MMM) platform connecting digital attribution to media budget modeling.", why:"Connects CCNA's digital MTA to offline MMM — enabling media budget decisions that account for brand TV, OOH, and digital together.", deploy:"SaaS", fit:"High", cost:"$60K–$100K/yr"},
          {n:"Triple Whale", cat:"Attribution Analytics", desc:"AI attribution analytics with real-time signal processing and automated bid optimization integration.", why:"Provides real-time attribution signals to Trade Desk and DV360 bid algorithms — enabling the autonomous budget reallocation CCNA currently cannot do.", deploy:"SaaS", fit:"Medium", cost:"$36K–$60K/yr"},
          {n:"Amplitude", cat:"Behavioral Analytics", desc:"Product and marketing analytics with deep behavioral signal processing and campaign attribution.", why:"Connects consumer behavioral signals from CCNA's digital properties back into the media attribution model for a more complete view.", deploy:"SaaS", fit:"Medium", cost:"$72K–$120K/yr"},
        ],
        benefits:{efficiency:55, roi:30, insight:10, risk:5},
      },
    ],
  },
  {
    id:"retail", label:"Retail Intelligence AI", icon:"◉", score:2.51, color:C.coral,
    status:"Nascent", tools:3, gapCount:2, roi:"$7.1M",
    goals:["AI shelf recognition across 3M+ retail points in North America","Route-to-market optimization reducing distribution cost 12%","Real-time OOS detection and automatic replenishment triggers","Connect retail data to marketing activation"],
    sources:[{n:"Trax Retail AI",t:"Shelf intelligence",s:"Pilot"},{n:"Blue Yonder AI",t:"Supply chain AI",s:"Live"},{n:"Salesforce B2B Commerce AI",t:"DSD optimization",s:"Evaluating"}],
    findings:[
      {sev:"high", text:"Trax shelf recognition pilot in 1,200 stores — less than 0.04% of North American retail footprint. No scale plan after 18 months of pilot data.", value:"$5.2M"},
      {sev:"medium", text:"Blue Yonder supply chain AI operating without integration to marketing campaign calendar — promotions creating demand spikes the AI cannot anticipate.", value:"$1.9M"},
    ],
    advisories:[
      {
        title:"Retail AI Scale Decision — Trax Deployment",
        priority:"P1", timeline:"180 days", annualValue:"$5.2M", investment:"$3.2M",
        finding:"18 months of pilot data from 1,200 Trax stores validates the technology. The scale decision is overdue. At current 0.04% coverage, the investment in piloting has not generated proportionate returns.",
        advisory:"Scale Trax to 50,000 stores (top 25% by volume) in 2026. Each 1% improvement in shelf presence in high-traffic stores = ~$8M incremental revenue in NA. ROI is demonstrably positive at scale. Simultaneously, implement the OOS-to-media-suppression bridge to immediately reclaim wasted ad spend.",
        whyNow:"Trax contract renewal is in Q3 2026. Scaling now captures the better price-per-store terms available in renewal negotiation. Meanwhile, PepsiCo has announced a full-chain retail AI deployment targeting 80% of their retail footprint by end of 2026.",
        disruption:"Retail AI is becoming table stakes in FMCG. Monster Energy's shelf recognition deployment in 2024 contributed to measurable shelf share gains versus Coca-Cola in convenience channel, attributed directly to faster OOS response.",
        roadmap:["Board approval for Trax scale investment (Week 1-2)","Negotiate expanded Trax contract at 50K store tier (Week 2-4)","Prioritize top 50K stores by volume contribution (Week 3-4)","Pilot OOS-to-media suppression connection with Google DV360 (Week 4-8)","Deploy Trax to 25K stores in priority markets (Month 3-4)","Complete 50K store deployment (Month 5-6)","Launch retail-to-marketing data pipeline live (Month 6)"],
        tools:[
          {n:"Trax", cat:"Retail AI", desc:"Computer vision-powered shelf recognition, OOS detection, and retail execution monitoring at scale.", why:"CCNA's existing pilot partner — scaling from 1,200 to 50,000 stores delivers shelf intelligence at a meaningful coverage level (top 25% by volume).", deploy:"SaaS + Edge", fit:"High", cost:"$2M–$4M (50K stores)"},
          {n:"RELEX Solutions", cat:"Supply Chain AI", desc:"AI-powered store-level demand forecasting with promotional lift modeling and supply chain optimization.", why:"Integrates CCNA's campaign calendar into Blue Yonder's replenishment algorithm — eliminating the 3-4 week demand spike blind spot during promotions.", deploy:"SaaS", fit:"High", cost:"$180K–$300K/yr"},
          {n:"Crisp", cat:"Retail Data", desc:"Real-time retail data connectivity platform aggregating POS, inventory, and shelf data from major retailers.", why:"Provides real-time Walmart, Target, and Kroger POS data to the media suppression system — enables OOS-to-ad-suppression in near real-time.", deploy:"SaaS", fit:"Medium", cost:"$60K–$100K/yr"},
          {n:"Google DV360 Audiences", cat:"Media Activation", desc:"Programmatic audience targeting and suppression using first-party and retail signals.", why:"Activates the retail-to-media suppression use case — stops serving ads to consumers in geographic markets where CCNA products are out of stock.", deploy:"Platform", fit:"Medium", cost:"Media % fee"},
        ],
        benefits:{revenue:55, efficiency:25, intelligence:15, risk:5},
      },
    ],
  },
  {
    id:"innovation", label:"Innovation & Forecasting", icon:"✺", score:2.18, color:C.emerald,
    status:"Nascent", tools:2, gapCount:1, roi:"$6.3M",
    goals:["Reduce NPD cycle from 18 to 9 months using AI-driven concept generation","Predict winning flavors and formats 12 months ahead","Real-time competitive product intelligence","Connect consumer signals to R&D prioritization"],
    sources:[{n:"Tastewise",t:"Food trend AI",s:"Pilot"},{n:"Mintel AI",t:"Market intelligence",s:"Live"}],
    findings:[
      {sev:"high", text:"NPD AI capability critically underdeveloped relative to company size — only 2 tools vs industry average 5.8 for equivalent R&D budgets.", value:"$5.8M"},
      {sev:"medium", text:"Innovation team not receiving real-time competitive product launches — manual monitoring creating 3-4 week awareness lag.", value:"$0.5M"},
    ],
    advisories:[
      {
        title:"Innovation AI Stack Build",
        priority:"P2", timeline:"270 days", annualValue:"$5.8M", investment:"$1.4M",
        finding:"CCNA runs 40+ new products annually in North America with only 2 AI tools supporting the entire innovation pipeline — vs industry average of 5.8. The innovation function is the highest-potential under-invested AI area in Marketing NA.",
        advisory:"Build a comprehensive Innovation AI stack in three phases: (1) Expand trend intelligence by scaling Tastewise and adding 2 complementary tools; (2) Implement competitive intelligence AI for real-time launch monitoring; (3) Connect trend signals to NPD prioritization workflow to create an AI-assisted innovation funnel.",
        whyNow:"Coca-Cola's innovation win rate has declined 4pp in the last 3 years while P&G's has improved 6pp — partially attributed to P&G's AI-powered NPD process launched in 2023. The window to close this gap is narrowing as AI-native competitors accelerate.",
        disruption:"AI-powered concept generation is cutting NPD cycles from 18+ months to 6-9 months at Unilever and Nestlé. Companies achieving sub-9-month NPD cycles are launching into trend windows that 18-month cycles miss entirely.",
        roadmap:["Complete Tastewise scale decision and expand to full category coverage (Month 1)","Evaluate and select competitive intelligence AI platform (Month 1-2)","Implement real-time competitive launch monitoring dashboard (Month 2-3)","Build NPD AI concept generation workflow with R&D team (Month 3-5)","Integrate trend signals into stage-gate process (Month 5-7)","Train innovation team on AI-augmented NPD process (Month 7-9)"],
        tools:[
          {n:"Tastewise", cat:"Trend Intelligence", desc:"AI-powered food and beverage trend detection using real-time signals from 30B+ social, recipe, and menu data points.", why:"CCNA's existing pilot — expanding to full category coverage gives the innovation team 12-month predictive signals for winning flavors and formats.", deploy:"SaaS", fit:"High", cost:"$48K–$80K/yr"},
          {n:"Innova Market Insights", cat:"Product Intelligence", desc:"Global product launch intelligence with 400K+ new product launches tracked annually across 100+ countries.", why:"Closes CCNA's 3-4 week competitive launch awareness lag — alerts innovation team within 24 hours of any competitor product launch globally.", deploy:"SaaS", fit:"High", cost:"$40K–$70K/yr"},
          {n:"Crayon", cat:"Competitive Intelligence", desc:"Real-time competitive intelligence platform tracking competitor product launches, pricing, messaging, and positioning.", why:"Monitors Pepsi, Monster, and emerging challenger brands across all channels — feeds competitive signals directly into CCNA's innovation stage-gate process.", deploy:"SaaS", fit:"High", cost:"$36K–$60K/yr"},
          {n:"Hype Auditor", cat:"Trend Validation", desc:"AI-powered trend validation using influencer and social signal data to predict consumer adoption curves.", why:"Validates Tastewise trend signals against actual consumer behavior — reduces false positive innovation bets before heavy R&D investment.", deploy:"SaaS", fit:"Medium", cost:"$24K–$40K/yr"},
        ],
        benefits:{speed:45, quality:30, intelligence:18, risk:7},
      },
    ],
  },
];

const ALL_FINDINGS = FUNCTIONS.flatMap(f => f.findings.map(fi => ({...fi, fn:f})));
const ALL_ADVISORIES = FUNCTIONS.flatMap(f => f.advisories.map(adv => ({...adv, fn:f})));

// ─── Helpers ─────────────────────────────────────────────────────────────────
const Pill = ({text, color, small}) => (
  <span style={{display:"inline-block", fontSize:small?9:10, fontWeight:700, color, border:`1px solid ${color}`,
    borderRadius:4, padding:small?"1px 5px":"2px 8px", letterSpacing:.8, opacity:.9}}>{text}</span>
);

const ScoreBar = ({value, max=5, color, h=5}) => (
  <div style={{background:C.dim, borderRadius:3, height:h, overflow:"hidden"}}>
    <div style={{width:`${(value/max)*100}%`, background:color, height:"100%", borderRadius:3}}/>
  </div>
);

const KpiCell = ({label, value, color}) => (
  <div style={{flex:1, background:C.bg, borderRadius:6, padding:"10px 12px", textAlign:"center", border:`1px solid ${C.border}`}}>
    <div style={{fontSize:9, color:C.off, letterSpacing:1, marginBottom:5}}>{label}</div>
    <div style={{fontSize:18, fontWeight:800, color}}>{value}</div>
  </div>
);

const SevColor = {high:C.coral, medium:C.amber, low:C.off};

// ─── Advisory Modal ──────────────────────────────────────────────────────────
function AdvisoryModal({adv, fn, onClose}) {
  if (!adv || !fn) return null;
  const [scenario, setScenario] = useState("base");
  const mult = {bear:.6, base:1, bull:1.45};
  const projVal = (parseFloat(adv.annualValue.replace("$","").replace("M","")) * mult[scenario]).toFixed(1);

  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.82)",zIndex:2000,display:"flex",alignItems:"flex-start",
      justifyContent:"center",paddingTop:24,paddingBottom:24,overflowY:"auto",fontFamily:FF}} onClick={onClose}>
      <div style={{background:C.card,borderRadius:12,border:`1px solid ${fn.color}40`,width:"92%",maxWidth:820,
        padding:28,position:"relative"}} onClick={e=>e.stopPropagation()}>

        {/* Close */}
        <button onClick={onClose} style={{position:"absolute",top:16,right:16,background:C.card2,border:`1px solid ${C.border}`,
          borderRadius:6,color:C.off,padding:"5px 10px",cursor:"pointer",fontSize:13,fontFamily:FF}}>✕</button>

        {/* Header badges */}
        <div style={{display:"flex",gap:8,marginBottom:12,flexWrap:"wrap"}}>
          <Pill text={adv.priority} color={adv.priority==="P1"?C.coral:adv.priority==="P2"?C.amber:C.off}/>
          <Pill text={adv.timeline} color={C.cyan}/>
          <Pill text={fn.label.substring(0,28)} color={fn.color}/>
          <Pill text="CLaiMB Advisory" color={C.teal}/>
        </div>

        <div style={{fontSize:20,fontWeight:800,color:C.white,marginBottom:4}}>{adv.title}</div>
        <div style={{fontSize:11,color:fn.color,marginBottom:18}}>Coca-Cola North America · {fn.label}</div>

        {/* KPI Row */}
        <div style={{display:"flex",gap:10,marginBottom:20}}>
          <KpiCell label="ANNUAL VALUE" value={`$${projVal}M`} color={C.emerald}/>
          <KpiCell label="TIMELINE" value={adv.timeline} color={C.cyan}/>
          <KpiCell label="INVESTMENT" value={adv.investment} color={C.amber}/>
          <KpiCell label="PRIORITY" value={adv.priority} color={adv.priority==="P1"?C.coral:C.amber}/>
        </div>

        {/* Finding + Advisory side by side */}
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16}}>
          <div style={{background:C.card2,borderRadius:8,padding:14,border:`1px solid ${C.border}`}}>
            <div style={{fontSize:9,fontWeight:700,color:C.coral,letterSpacing:1,marginBottom:8}}>CLaiMB FINDING</div>
            <div style={{fontSize:12,color:C.off,lineHeight:1.7}}>{adv.finding}</div>
          </div>
          <div style={{background:C.card2,borderRadius:8,padding:14,border:`1px solid ${C.border}`}}>
            <div style={{fontSize:9,fontWeight:700,color:C.teal,letterSpacing:1,marginBottom:8}}>CLaiMB ADVISORY</div>
            <div style={{fontSize:12,color:C.white,lineHeight:1.7}}>{adv.advisory}</div>
          </div>
        </div>

        {/* Why Act Now */}
        <div style={{background:`${C.amber}12`,border:`1px solid ${C.amber}30`,borderRadius:8,padding:14,marginBottom:12}}>
          <div style={{fontSize:9,fontWeight:700,color:C.amber,letterSpacing:1,marginBottom:6}}>⚡ WHY ACT NOW</div>
          <div style={{fontSize:12,color:C.white,lineHeight:1.7}}>{adv.whyNow}</div>
        </div>

        {/* Disruption Intelligence */}
        <div style={{background:`${fn.color}0F`,border:`1px solid ${fn.color}28`,borderRadius:8,padding:14,marginBottom:16}}>
          <div style={{fontSize:9,fontWeight:700,color:fn.color,letterSpacing:1,marginBottom:6}}>◇ DISRUPTION INTELLIGENCE</div>
          <div style={{fontSize:12,color:C.white,lineHeight:1.7}}>{adv.disruption}</div>
        </div>

        {/* TOOLS & SOLUTIONS — full-width rich cards */}
        <div style={{marginBottom:16}}>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12}}>
            <div style={{fontSize:9,fontWeight:700,color:C.off,letterSpacing:1}}>TOOLS & SOLUTIONS</div>
            <span style={{fontSize:9,color:C.dim}}>CLaiMB-curated for this gap</span>
          </div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",gap:10}}>
            {(adv.tools||[]).map((t,i)=>{
              const fitColor = t.fit==="High"?C.emerald:t.fit==="Medium"?C.amber:C.off;
              return (
              <div key={i} style={{background:C.card2,borderRadius:8,padding:14,border:`1px solid ${C.border}`,
                borderLeft:`3px solid ${fitColor}`,display:"flex",flexDirection:"column",gap:6}}>
                {/* Header row */}
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                  <span style={{fontSize:13,fontWeight:800,color:C.white}}>{t.n}</span>
                  <div style={{display:"flex",gap:6}}>
                    {t.cat&&<span style={{fontSize:9,color:fn.color,border:`1px solid ${fn.color}40`,
                      borderRadius:4,padding:"1px 6px",fontWeight:600}}>{t.cat}</span>}
                    {t.deploy&&<span style={{fontSize:9,color:C.off,border:`1px solid ${C.border}`,
                      borderRadius:4,padding:"1px 6px"}}>{t.deploy}</span>}
                    <span style={{fontSize:9,color:fitColor,border:`1px solid ${fitColor}50`,
                      borderRadius:4,padding:"1px 6px",fontWeight:700}}>{t.fit||"High"} fit</span>
                  </div>
                </div>
                {/* Description */}
                <div style={{fontSize:11,color:C.off,lineHeight:1.55}}>{t.desc}</div>
                {/* Cost estimate */}
                {t.cost&&<div style={{display:"flex",alignItems:"center",gap:6}}>
                  <span style={{fontSize:9,color:C.dim,letterSpacing:.5}}>EST. ANNUAL COST</span>
                  <span style={{fontSize:11,fontWeight:700,color:C.amber}}>{t.cost}</span>
                </div>}
                {/* CLaiMB why */}
                {t.why&&<div style={{background:`${fn.color}0C`,borderRadius:5,padding:"7px 9px",
                  borderLeft:`2px solid ${fn.color}60`}}>
                  <span style={{fontSize:9,fontWeight:700,color:fn.color,letterSpacing:.5}}>WHY CLaiMB RECOMMENDS  </span>
                  <span style={{fontSize:10,color:C.white,lineHeight:1.5}}>{t.why}</span>
                </div>}
              </div>
            );})}
          </div>
        </div>

        <div style={{display:"grid",gridTemplateColumns:"1.2fr 1fr",gap:14,marginBottom:16}}>
          {/* Roadmap */}
          <div>
            <div style={{fontSize:9,fontWeight:700,color:C.off,letterSpacing:1,marginBottom:10}}>IMPLEMENTATION ROADMAP</div>
            {(adv.roadmap||[]).map((step,i)=>(
              <div key={i} style={{display:"flex",gap:10,marginBottom:10,alignItems:"flex-start"}}>
                <div style={{width:22,height:22,borderRadius:"50%",background:fn.color,color:"#000",
                  display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:800,flexShrink:0}}>{i+1}</div>
                <div style={{fontSize:11,color:C.off,lineHeight:1.5,paddingTop:2}}>{step}</div>
              </div>
            ))}
          </div>

          {/* Benefits + Scenario */}
          <div>
            <div style={{fontSize:9,fontWeight:700,color:C.off,letterSpacing:1,marginBottom:10}}>BENEFIT DECOMPOSITION</div>
            {Object.entries(adv.benefits||{}).map(([k,v])=>(
              <div key={k} style={{marginBottom:7}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:3}}>
                  <span style={{fontSize:10,color:C.off,textTransform:"capitalize"}}>{k}</span>
                  <span style={{fontSize:10,fontWeight:700,color:fn.color}}>{v}%</span>
                </div>
                <ScoreBar value={v} max={100} color={fn.color} h={4}/>
              </div>
            ))}

            <div style={{marginTop:14}}>
              <div style={{fontSize:9,fontWeight:700,color:C.off,letterSpacing:1,marginBottom:8}}>SCENARIO</div>
              <div style={{display:"flex",gap:6}}>
                {["bear","base","bull"].map(s=>(
                  <button key={s} onClick={()=>setScenario(s)}
                    style={{flex:1,background:scenario===s?fn.color:C.card2,border:`1px solid ${scenario===s?fn.color:C.border}`,
                      borderRadius:5,color:scenario===s?"#000":C.off,padding:"5px 0",cursor:"pointer",
                      fontSize:10,fontWeight:700,fontFamily:FF,textTransform:"capitalize"}}>{s}</button>
                ))}
              </div>
              <div style={{marginTop:8,textAlign:"center",fontSize:13,fontWeight:700,color:C.emerald}}>
                Projected value: ${projVal}M / year
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Sidebar ─────────────────────────────────────────────────────────────────
function Sidebar({page, setPage}) {
  const highCount = ALL_FINDINGS.filter(f=>f.sev==="high").length;
  const advCount = ALL_ADVISORIES.length;

  const Section = ({label}) => (
    <div style={{fontSize:9,fontWeight:700,color:C.dim,letterSpacing:1.5,padding:"16px 16px 5px",textTransform:"uppercase"}}>{label}</div>
  );

  const NavItem = ({id, icon, label, badge, badgeColor}) => {
    const active = page === id;
    return (
      <div onClick={()=>setPage(id)} style={{display:"flex",alignItems:"center",justifyContent:"space-between",
        padding:"8px 16px",borderRadius:6,margin:"1px 8px",cursor:"pointer",
        background:active?`${C.teal}18`:undefined,
        borderLeft:active?`2px solid ${C.teal}`:"2px solid transparent"}}>
        <div style={{display:"flex",alignItems:"center",gap:10}}>
          <span style={{fontSize:14,color:active?C.teal:C.off}}>{icon}</span>
          <span style={{fontSize:12,fontWeight:active?700:400,color:active?C.white:C.off}}>{label}</span>
        </div>
        {badge != null && (
          <span style={{background:badgeColor,borderRadius:10,padding:"1px 7px",fontSize:9,
            fontWeight:700,color:"#000",minWidth:18,textAlign:"center"}}>{badge}</span>
        )}
        {id==="ask" && (
          <span style={{background:C.violet,borderRadius:10,padding:"1px 7px",fontSize:9,fontWeight:700,color:"#fff"}}>AI</span>
        )}
      </div>
    );
  };

  return (
    <div style={{width:220,flexShrink:0,background:C.sbg,borderRight:`1px solid ${C.border}`,
      display:"flex",flexDirection:"column",height:"100vh",overflowY:"auto",position:"sticky",top:0,fontFamily:FF}}>

      {/* Company badge */}
      <div style={{padding:"16px",borderBottom:`1px solid ${C.border}`}}>
        <div style={{fontSize:13,fontWeight:800,color:C.teal,letterSpacing:-.3,marginBottom:2}}>CLaiMB.ai</div>
        <div style={{fontSize:11,fontWeight:700,color:C.white,marginBottom:1}}>Coca-Cola North America</div>
        <div style={{fontSize:10,color:C.off,marginBottom:10}}>Marketing · Enterprise · Confidential</div>
        {/* Score vs peer */}
        <div style={{display:"flex",justifyContent:"space-between",marginBottom:4}}>
          <span style={{fontSize:10,color:C.off}}>AIMRI™ Score</span>
          <span style={{fontSize:11,fontWeight:700,color:C.amber}}>{PEER_SCORE} / 5.0</span>
        </div>
        <div style={{background:C.dim,borderRadius:3,height:6,position:"relative",marginBottom:4}}>
          <div style={{width:`${(PEER_SCORE/5)*100}%`,background:C.amber,height:"100%",borderRadius:3}}/>
          {/* peer marker */}
          <div style={{position:"absolute",top:-3,left:`${(3.71/5)*100}%`,width:2,height:12,background:C.emerald,borderRadius:1}}/>
        </div>
        <div style={{display:"flex",justifyContent:"space-between"}}>
          <span style={{fontSize:9,color:C.off}}>▲ P&G: 3.71</span>
          <span style={{fontSize:9,color:C.emerald}}>Sector leader</span>
        </div>
      </div>

      {/* Nav */}
      <div style={{flex:1,overflowY:"auto",paddingBottom:16}}>
        <Section label="Overview"/>
        <NavItem id="dashboard" icon="⊞" label="Dashboard"/>

        <Section label="AI Assessment"/>
        <NavItem id="functions" icon="◈" label="Business Functions"/>
        <NavItem id="readiness" icon="◷" label="Readiness & Maturity"/>

        <Section label="Analysis"/>
        <NavItem id="findings" icon="△" label="Findings" badge={highCount} badgeColor={C.coral}/>
        <NavItem id="advisory" icon="◇" label="Advisory" badge={advCount} badgeColor={C.amber}/>
        <NavItem id="roi" icon="$" label="ROI Planner"/>

        <Section label="Intelligence"/>
        <NavItem id="ask" icon="✦" label="Ask CLaiMB"/>
      </div>

      {/* Footer */}
      <div style={{padding:"10px 16px",borderTop:`1px solid ${C.border}`}}>
        <div style={{display:"flex",alignItems:"center",gap:6}}>
          <div style={{width:7,height:7,borderRadius:"50%",background:C.emerald}}/>
          <span style={{fontSize:10,color:C.off}}>Live · Synced now · {FUNCTIONS.reduce((a,f)=>a+f.sources.length,0)} sources</span>
        </div>
      </div>
    </div>
  );
}

// ─── Pages ───────────────────────────────────────────────────────────────────
function PageHeader({title, sub}) {
  return (
    <div style={{marginBottom:22}}>
      <div style={{fontSize:20,fontWeight:800,color:C.white,marginBottom:4}}>{title}</div>
      {sub && <div style={{fontSize:12,color:C.off}}>{sub}</div>}
    </div>
  );
}

function Dashboard({setPage, openAdvisory}) {
  const highCount = ALL_FINDINGS.filter(f=>f.sev==="high").length;
  return (
    <div>
      <PageHeader title="Dashboard" sub="Coca-Cola North America · Marketing AI Intelligence · Q2 2026"/>
      {/* Hero metrics */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginBottom:20}}>
        {[
          {l:"AIMRI™ Score",v:"3.24 / 5.0",sub:"+0.18 vs last quarter",c:C.amber},
          {l:"Active AI Tools",v:"23",sub:"Across 6 marketing functions",c:C.teal},
          {l:"High-Priority Gaps",v:String(highCount),sub:"Requiring immediate action",c:C.coral},
          {l:"Projected ROI",v:"$48M",sub:"If all gaps closed by Q4",c:C.emerald},
        ].map((m,i)=>(
          <div key={i} style={{background:C.card,border:`1px solid ${C.border}`,borderTop:`3px solid ${m.c}`,borderRadius:8,padding:"14px 16px"}}>
            <div style={{fontSize:9,color:C.off,letterSpacing:1,marginBottom:6,fontWeight:600}}>{m.l}</div>
            <div style={{fontSize:26,fontWeight:800,color:m.c,lineHeight:1.1}}>{m.v}</div>
            <div style={{fontSize:10,color:C.dim,marginTop:5}}>{m.sub}</div>
          </div>
        ))}
      </div>

      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14,marginBottom:14}}>
        {/* Peer benchmark */}
        <div style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18}}>
          <div style={{fontSize:9,color:C.off,letterSpacing:1,fontWeight:600,marginBottom:14}}>AIMRI™ PEER BENCHMARK — FMCG / BEVERAGE</div>
          {PEERS.map((p,i)=>(
            <div key={i} style={{display:"flex",alignItems:"center",gap:10,marginBottom:9}}>
              <div style={{width:100,fontSize:11,fontWeight:p.you?700:400,color:p.you?C.amber:C.off,flexShrink:0}}>{p.name}</div>
              <div style={{flex:1,background:C.card2,borderRadius:3,height:7,overflow:"hidden"}}>
                <div style={{width:`${(p.score/5)*100}%`,background:p.you?C.amber:p.c,height:"100%",opacity:p.you?1:.45,borderRadius:3}}/>
              </div>
              <div style={{width:30,fontSize:11,fontWeight:p.you?700:400,color:p.you?C.amber:C.off,textAlign:"right"}}>{p.score}</div>
            </div>
          ))}
        </div>

        {/* Function scores */}
        <div style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18}}>
          <div style={{fontSize:9,color:C.off,letterSpacing:1,fontWeight:600,marginBottom:14}}>MARKETING FUNCTION SCORES</div>
          {FUNCTIONS.map(f=>(
            <div key={f.id} style={{display:"flex",alignItems:"center",gap:10,marginBottom:11,cursor:"pointer"}} onClick={()=>setPage("functions")}>
              <span style={{fontSize:14,color:f.color,flexShrink:0}}>{f.icon}</span>
              <div style={{flex:1}}>
                <div style={{fontSize:11,color:C.white,marginBottom:3}}>{f.label}</div>
                <ScoreBar value={f.score} color={f.color}/>
              </div>
              <div style={{width:34,fontSize:12,fontWeight:700,color:f.color,textAlign:"right"}}>{f.score}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Top findings */}
      <div style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18}}>
        <div style={{fontSize:9,color:C.off,letterSpacing:1,fontWeight:600,marginBottom:14}}>HIGH-PRIORITY FINDINGS — IMMEDIATE ACTION REQUIRED</div>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
          {ALL_FINDINGS.filter(f=>f.sev==="high").map((f,i)=>(
            <div key={i} style={{background:C.card2,borderLeft:`3px solid ${f.fn.color}`,borderRadius:6,padding:14}}>
              <div style={{fontSize:9,color:f.fn.color,fontWeight:700,letterSpacing:1,marginBottom:5}}>{f.fn.label.toUpperCase()}</div>
              <div style={{fontSize:11,color:C.white,lineHeight:1.55,marginBottom:8}}>{f.text.substring(0,110)}{f.text.length>110?"…":""}</div>
              <div style={{display:"flex",gap:8,alignItems:"center"}}>
                <Pill text="HIGH" color={C.coral} small/>
                <Pill text={`ROI: ${f.value}`} color={C.emerald} small/>
                <button onClick={()=>openAdvisory(f.fn.advisories[0],f.fn)} style={{marginLeft:"auto",background:"none",
                  border:`1px solid ${f.fn.color}`,borderRadius:4,color:f.fn.color,padding:"2px 8px",cursor:"pointer",fontSize:10,fontFamily:FF}}>
                  Advisory →
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function FunctionsPage({openAdvisory}) {
  const [sel, setSel] = useState(null);
  const [tab, setTab] = useState("findings");

  if (!sel) return (
    <div>
      <PageHeader title="Business Functions" sub="6 marketing AI areas assessed across Coca-Cola North America"/>
      <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:12}}>
        {FUNCTIONS.map(f=>(
          <div key={f.id} style={{background:C.card,border:`1px solid ${C.border}`,borderTop:`3px solid ${f.color}`,
            borderRadius:8,padding:18,cursor:"pointer"}} onClick={()=>{setSel(f);setTab("findings");}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:12}}>
              <span style={{fontSize:22,color:f.color}}>{f.icon}</span>
              <Pill text={f.status} color={f.color}/>
            </div>
            <div style={{fontSize:15,fontWeight:700,color:C.white,marginBottom:5}}>{f.label}</div>
            <div style={{fontSize:28,fontWeight:800,color:f.color,marginBottom:10}}>{f.score}<span style={{fontSize:13,color:C.off}}>/5.0</span></div>
            <ScoreBar value={f.score} color={f.color}/>
            <div style={{display:"flex",gap:14,marginTop:12}}>
              <span style={{fontSize:11,color:C.off}}><b style={{color:f.color}}>{f.tools}</b> tools</span>
              <span style={{fontSize:11,color:C.off}}><b style={{color:C.coral}}>{f.gapCount}</b> gaps</span>
              <span style={{fontSize:11,color:C.off}}><b style={{color:C.emerald}}>{f.roi}</b> ROI</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  const TABS = ["goals","sources","findings","advisory","businessCase","readiness"];
  return (
    <div>
      <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:18}}>
        <button onClick={()=>setSel(null)} style={{background:C.card2,border:`1px solid ${C.border}`,borderRadius:6,
          color:C.off,padding:"6px 14px",cursor:"pointer",fontSize:12,fontFamily:FF}}>← Back</button>
        <span style={{fontSize:20,color:sel.color}}>{sel.icon}</span>
        <div>
          <div style={{fontSize:17,fontWeight:700,color:C.white}}>{sel.label}</div>
          <div style={{fontSize:11,color:C.off}}>Score: <b style={{color:sel.color}}>{sel.score}/5.0</b> · {sel.status}</div>
        </div>
      </div>

      <div style={{display:"flex",borderBottom:`1px solid ${C.border}`,marginBottom:18}}>
        {TABS.map(t=>(
          <button key={t} onClick={()=>setTab(t)} style={{background:"none",border:"none",
            borderBottom:tab===t?`2px solid ${sel.color}`:"2px solid transparent",
            color:tab===t?sel.color:C.off,padding:"9px 16px",cursor:"pointer",fontSize:11,
            fontWeight:tab===t?700:400,textTransform:"capitalize",fontFamily:FF}}>
            {t==="businessCase"?"Business Case":t==="findings"?"Findings":t.charAt(0).toUpperCase()+t.slice(1)}
          </button>
        ))}
      </div>

      {tab==="goals" && (
        <div>
          {sel.goals.map((g,i)=>(
            <div key={i} style={{display:"flex",gap:12,background:C.card,border:`1px solid ${C.border}`,
              borderLeft:`3px solid ${sel.color}`,borderRadius:6,padding:14,marginBottom:10}}>
              <div style={{width:24,height:24,borderRadius:"50%",background:sel.color,color:"#000",display:"flex",
                alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:800,flexShrink:0}}>{i+1}</div>
              <span style={{fontSize:13,color:C.white,lineHeight:1.6}}>{g}</span>
            </div>
          ))}
        </div>
      )}

      {tab==="sources" && (
        <div style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",gap:10}}>
          {sel.sources.map((s,i)=>(
            <div key={i} style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:6,padding:14,
              display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div>
                <div style={{fontSize:13,fontWeight:700,color:C.white,marginBottom:3}}>{s.n}</div>
                <div style={{fontSize:11,color:C.off}}>{s.t}</div>
              </div>
              <Pill text={s.s} color={s.s==="Live"?C.emerald:s.s==="Scaling"?C.teal:s.s==="Pilot"?C.amber:C.dim}/>
            </div>
          ))}
        </div>
      )}

      {tab==="findings" && (
        <div>
          {sel.findings.map((f,i)=>(
            <div key={i} style={{background:C.card,border:`1px solid ${C.border}`,
              borderLeft:`3px solid ${SevColor[f.sev]}`,borderRadius:6,padding:16,marginBottom:12}}>
              <div style={{display:"flex",gap:10,alignItems:"center",marginBottom:8}}>
                <Pill text={f.sev.toUpperCase()} color={SevColor[f.sev]}/>
                <span style={{fontSize:10,color:C.dim}}>Finding {i+1} · Est. value: <b style={{color:C.emerald}}>{f.value}</b></span>
              </div>
              <div style={{fontSize:13,color:C.white,lineHeight:1.6}}>{f.text}</div>
              {sel.advisories.length > 0 && (
                <button onClick={()=>openAdvisory(sel.advisories[0],sel)} style={{marginTop:10,background:"none",
                  border:`1px solid ${sel.color}`,borderRadius:5,color:sel.color,padding:"4px 12px",
                  cursor:"pointer",fontSize:11,fontFamily:FF}}>View Advisory →</button>
              )}
            </div>
          ))}
        </div>
      )}

      {tab==="advisory" && (
        <div>
          {sel.advisories.map((adv,i)=>(
            <div key={i} style={{background:C.card,border:`1px solid ${sel.color}`,borderRadius:8,padding:20,marginBottom:14}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
                <div>
                  <div style={{fontSize:15,fontWeight:700,color:C.white,marginBottom:3}}>{adv.title}</div>
                  <div style={{display:"flex",gap:8}}>
                    <Pill text={adv.priority} color={adv.priority==="P1"?C.coral:C.amber} small/>
                    <Pill text={adv.timeline} color={C.cyan} small/>
                    <Pill text={adv.annualValue+" value"} color={C.emerald} small/>
                  </div>
                </div>
                <button onClick={()=>openAdvisory(adv,sel)} style={{background:sel.color,border:"none",borderRadius:6,
                  color:"#000",padding:"8px 16px",cursor:"pointer",fontSize:12,fontWeight:700,fontFamily:FF}}>
                  Open Detail ↗
                </button>
              </div>
              <div style={{fontSize:12,color:C.off,lineHeight:1.6}}>{adv.advisory.substring(0,200)}…</div>
            </div>
          ))}
          {sel.advisories.length===0 && <div style={{color:C.off,fontSize:13}}>No advisories yet for this function.</div>}
        </div>
      )}

      {tab==="businessCase" && (
        <div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:10,marginBottom:16}}>
            {[
              {l:"Investment",v:sel.advisories[0]?.investment||"TBD",c:C.amber},
              {l:"Year 1 ROI",v:sel.roi,c:C.emerald},
              {l:"3-Year ROI",v:`$${(parseFloat((sel.roi||"0").replace(/[$M]/g,""))*3.2).toFixed(0)}M`,c:C.teal},
              {l:"Payback",v:"8-12 months",c:C.cyan},
              {l:"Confidence",v:sel.score>3.4?"High":sel.score>2.7?"Medium":"Low",c:sel.color},
            ].map((m,i)=>(
              <div key={i} style={{background:C.card,border:`1px solid ${C.border}`,borderTop:`2px solid ${m.c}`,
                borderRadius:7,padding:14,textAlign:"center"}}>
                <div style={{fontSize:9,color:C.off,marginBottom:6}}>{m.l.toUpperCase()}</div>
                <div style={{fontSize:20,fontWeight:800,color:m.c}}>{m.v}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab==="readiness" && (
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16}}>
          <div style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18}}>
            <div style={{fontSize:9,color:C.off,letterSpacing:1,fontWeight:600,marginBottom:14}}>IMPLEMENTATION READINESS</div>
            {[["Data Readiness",sel.score>3.5?85:sel.score>2.8?65:50],
              ["Technology Readiness",sel.score>3.5?90:sel.score>2.8?70:55],
              ["Talent Readiness",sel.score>3.5?75:sel.score>2.8?62:50],
              ["Process Readiness",sel.score>3.5?60:sel.score>2.8?45:35],
              ["Governance",sel.score>3.5?42:sel.score>2.8?38:28]].map(([label,val],i)=>(
              <div key={i} style={{marginBottom:10}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:3}}>
                  <span style={{fontSize:11,color:C.off}}>{label}</span>
                  <span style={{fontSize:11,fontWeight:700,color:val>=70?C.emerald:val>=50?C.amber:C.coral}}>{val}%</span>
                </div>
                <ScoreBar value={val} max={100} color={val>=70?C.emerald:val>=50?C.amber:C.coral}/>
              </div>
            ))}
          </div>
          <div style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18}}>
            <div style={{fontSize:9,color:C.off,letterSpacing:1,fontWeight:600,marginBottom:14}}>KEY ACTIONS NEEDED</div>
            {(sel.advisories[0]?.roadmap||["Review implementation plan","Assign ownership","Define success metrics"]).slice(0,3).map((step,i)=>(
              <div key={i} style={{background:C.card2,borderRadius:6,padding:12,marginBottom:10,borderLeft:`3px solid ${sel.color}`}}>
                <div style={{fontSize:11,fontWeight:700,color:sel.color,marginBottom:3}}>Step {i+1}</div>
                <div style={{fontSize:11,color:C.off}}>{step}</div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function FindingsPage({openAdvisory}) {
  const [filter, setFilter] = useState("all");
  const filtered = filter==="all"?ALL_FINDINGS:ALL_FINDINGS.filter(f=>f.sev===filter);
  return (
    <div>
      <PageHeader title="Findings" sub={`${ALL_FINDINGS.length} findings across 6 marketing functions`}/>
      <div style={{display:"flex",gap:8,marginBottom:18}}>
        {["all","high","medium","low"].map(s=>(
          <button key={s} onClick={()=>setFilter(s)} style={{background:filter===s?SevColor[s]||C.teal:C.card2,
            border:`1px solid ${SevColor[s]||C.border}`,borderRadius:6,
            color:filter===s?"#000":C.off,padding:"5px 14px",cursor:"pointer",fontSize:11,fontWeight:700,fontFamily:FF,textTransform:"capitalize"}}>
            {s==="all"?"All":s.charAt(0).toUpperCase()+s.slice(1)+" ({count})".replace("{count}",ALL_FINDINGS.filter(f=>f.sev===s).length)}
          </button>
        ))}
      </div>
      {filtered.map((f,i)=>(
        <div key={i} style={{background:C.card,border:`1px solid ${C.border}`,borderLeft:`3px solid ${SevColor[f.sev]}`,
          borderRadius:6,padding:16,marginBottom:12,display:"flex",gap:14,alignItems:"flex-start"}}>
          <Pill text={f.sev.toUpperCase()} color={SevColor[f.sev]}/>
          <div style={{flex:1}}>
            <div style={{fontSize:10,color:f.fn.color,fontWeight:700,letterSpacing:1,marginBottom:5}}>{f.fn.label.toUpperCase()}</div>
            <div style={{fontSize:13,color:C.white,lineHeight:1.6}}>{f.text}</div>
          </div>
          <div style={{flexShrink:0,display:"flex",gap:8,alignItems:"center"}}>
            <Pill text={f.value} color={C.emerald} small/>
            <button onClick={()=>openAdvisory(f.fn.advisories[0]||{},f.fn)}
              style={{background:"none",border:`1px solid ${f.fn.color}`,borderRadius:5,color:f.fn.color,
                padding:"4px 10px",cursor:"pointer",fontSize:10,fontFamily:FF}}>Advisory →</button>
          </div>
        </div>
      ))}
    </div>
  );
}

function AdvisoryPage({openAdvisory}) {
  return (
    <div>
      <PageHeader title="Advisory" sub={`${ALL_ADVISORIES.length} strategic recommendations across all marketing functions`}/>
      {ALL_ADVISORIES.map((adv,i)=>(
        <div key={i} style={{background:C.card,border:`1px solid ${adv.fn.color}40`,borderRadius:8,padding:20,marginBottom:14}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:12}}>
            <div>
              <div style={{fontSize:10,color:adv.fn.color,fontWeight:700,letterSpacing:1,marginBottom:5}}>{adv.fn.label.toUpperCase()}</div>
              <div style={{fontSize:15,fontWeight:700,color:C.white,marginBottom:6}}>{adv.title}</div>
              <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
                <Pill text={adv.priority} color={adv.priority==="P1"?C.coral:C.amber} small/>
                <Pill text={adv.timeline} color={C.cyan} small/>
                <Pill text={`Value: ${adv.annualValue}`} color={C.emerald} small/>
                <Pill text={`Invest: ${adv.investment}`} color={C.amber} small/>
              </div>
            </div>
            <button onClick={()=>openAdvisory(adv,adv.fn)} style={{background:adv.fn.color,border:"none",borderRadius:6,
              color:"#000",padding:"8px 18px",cursor:"pointer",fontSize:12,fontWeight:700,fontFamily:FF,flexShrink:0}}>
              Full Detail ↗
            </button>
          </div>
          <div style={{background:C.card2,borderRadius:6,padding:12}}>
            <div style={{fontSize:9,color:C.off,letterSpacing:1,marginBottom:5}}>CLaiMB ADVISORY SUMMARY</div>
            <div style={{fontSize:12,color:C.off,lineHeight:1.65}}>{adv.advisory.substring(0,220)}…</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function RoiPage() {
  const [investments, setInvestments] = useState(
    Object.fromEntries(FUNCTIONS.map(f=>[f.id, parseFloat((f.advisories[0]?.investment||"$1M").replace(/[$MK]/g,m=>m==="K"?"/1000":""))]))
  );
  // Fix: parse properly
  const parseInv = str => {
    if (!str) return 1;
    const n = parseFloat(str.replace("$","").replace("M","").replace("K","")); 
    return str.includes("K")?n/1000:n;
  };
  const [inv2] = useState(Object.fromEntries(FUNCTIONS.map(f=>[f.id,parseInv(f.advisories[0]?.investment||"$1M")])));
  const [sliders, setSliders] = useState({...inv2});
  const totalInv = Object.values(sliders).reduce((a,b)=>a+b,0);
  const totalROI = FUNCTIONS.reduce((acc,f)=>{
    const base = parseFloat(f.roi.replace("$","").replace("M",""));
    const ratio = sliders[f.id]/(inv2[f.id]||1);
    return acc + base * Math.min(ratio,1.4);
  },0);

  return (
    <div>
      <PageHeader title="ROI Planner" sub="Adjust investment levels and see projected returns across all marketing AI functions"/>
      <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:12,marginBottom:20}}>
        {[
          {l:"Total Investment",v:`$${totalInv.toFixed(1)}M`,c:C.amber},
          {l:"Projected Y1 ROI",v:`$${totalROI.toFixed(1)}M`,c:C.emerald},
          {l:"Return Multiple",v:`${(totalROI/totalInv).toFixed(1)}×`,c:C.teal},
        ].map((m,i)=>(
          <div key={i} style={{background:C.card,border:`1px solid ${C.border}`,borderTop:`3px solid ${m.c}`,
            borderRadius:8,padding:"16px 20px",textAlign:"center"}}>
            <div style={{fontSize:9,color:C.off,letterSpacing:1,marginBottom:7}}>{m.l.toUpperCase()}</div>
            <div style={{fontSize:30,fontWeight:800,color:m.c}}>{m.v}</div>
          </div>
        ))}
      </div>
      {FUNCTIONS.map(f=>{
        const base = parseFloat(f.roi.replace("$","").replace("M",""));
        const ratio = sliders[f.id]/(inv2[f.id]||1);
        const proj = (base*Math.min(ratio,1.4)).toFixed(1);
        return (
          <div key={f.id} style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18,marginBottom:12}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
              <div style={{display:"flex",gap:10,alignItems:"center"}}>
                <span style={{color:f.color,fontSize:18}}>{f.icon}</span>
                <span style={{fontSize:14,fontWeight:700,color:C.white}}>{f.label}</span>
              </div>
              <div style={{display:"flex",gap:20}}>
                <div style={{textAlign:"right"}}>
                  <div style={{fontSize:9,color:C.off}}>INVESTED</div>
                  <div style={{fontSize:16,fontWeight:800,color:f.color}}>${sliders[f.id].toFixed(1)}M</div>
                </div>
                <div style={{textAlign:"right"}}>
                  <div style={{fontSize:9,color:C.off}}>PROJ ROI</div>
                  <div style={{fontSize:16,fontWeight:800,color:C.emerald}}>${proj}M</div>
                </div>
              </div>
            </div>
            <input type="range" min={0} max={5} step={0.1} value={sliders[f.id]}
              onChange={e=>setSliders(prev=>({...prev,[f.id]:parseFloat(e.target.value)}))}
              style={{width:"100%",accentColor:f.color}}/>
            <div style={{display:"flex",justifyContent:"space-between",fontSize:9,color:C.dim,marginTop:3}}>
              <span>$0M</span><span>$2.5M</span><span>$5M</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ReadinessPage() {
  return (
    <div>
      <PageHeader title="Readiness & Maturity" sub="AI transformation readiness across all marketing dimensions"/>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
        {FUNCTIONS.map(f=>(
          <div key={f.id} style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:8,padding:18}}>
            <div style={{display:"flex",gap:10,alignItems:"center",marginBottom:14}}>
              <span style={{fontSize:18,color:f.color}}>{f.icon}</span>
              <div>
                <div style={{fontSize:13,fontWeight:700,color:C.white}}>{f.label}</div>
                <Pill text={f.status} color={f.color} small/>
              </div>
              <div style={{marginLeft:"auto",fontSize:22,fontWeight:800,color:f.color}}>{f.score}</div>
            </div>
            {[["Strategy & Goals",f.score*18],["Data & Sources",f.score*17],
              ["Technology",f.score*19],["Talent",f.score*16],["Governance",f.score*10]].map(([dim,pct],i)=>(
              <div key={i} style={{marginBottom:8}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:3}}>
                  <span style={{fontSize:10,color:C.off}}>{dim}</span>
                  <span style={{fontSize:10,fontWeight:700,color:pct>=70?C.emerald:pct>=50?C.amber:C.coral}}>{Math.round(pct)}%</span>
                </div>
                <ScoreBar value={pct} max={100} color={pct>=70?C.emerald:pct>=50?C.amber:C.coral} h={5}/>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

function AskPage() {
  const [q, setQ] = useState("");
  const [log, setLog] = useState([{role:"ai",text:"Hello — I'm Ask CLaiMB, your Marketing AI intelligence assistant.\n\nI have full context on Coca-Cola North America's AI transformation across all 6 marketing functions, AIMRI™ scores, peer benchmarks vs P&G, Pepsi, and Unilever, and all 14 identified gaps with their projected ROI.\n\nWhat would you like to explore?"}]);
  const [loading, setLoading] = useState(false);
  const ref = useRef(null);
  useEffect(()=>ref.current?.scrollIntoView({behavior:"smooth"}),[log]);

  const SAMPLES = [
    "Where is CCNA's biggest gap vs Pepsi?",
    "Which investment delivers the fastest ROI?",
    "What's blocking our personalization score?",
    "Give me a board summary of Content AI",
    "How does our Insights score compare to P&G?",
  ];

  const send = async (text) => {
    const q2 = (text||q).trim();
    if (!q2 || loading) return;
    setQ("");
    setLog(l=>[...l,{role:"user",text:q2}]);
    setLoading(true);
    const sys = `You are Ask CLaiMB, the AI assistant for the CLaiMB Marketing AI Intelligence Platform for Coca-Cola North America (CCNA). AIMRI™ score: 3.24/5.0. Peer rankings: P&G 3.71, Unilever 3.44, CCNA 3.24, Pepsi 3.02, AB InBev 2.83. Six functions: Content & Creative AI (3.82 — Advanced, 7 tools, Gov gap = $8M), Consumer Insights AI (3.61 — Advanced, insight-to-activation 6-8wk gap = $6.2M), Personalization (3.02 — Opp Gap, AEP 22% unified = $8.8M gap), Media Optimization (2.84 — Opp Gap, last-click attribution 60% = $5.2M), Retail Intelligence (2.51 — Nascent, Trax in 0.04% stores = $5.2M), Innovation (2.18 — Nascent, 2 tools vs avg 5.8 = $5.8M). Total projected ROI: $48M. Respond as a confident, data-driven advisor. Be specific, cite numbers, use markdown.`;
    try {
      const res = await fetch("/api/ask",{method:"POST",
        headers:{"Content-Type":"application/json"},
        body:JSON.stringify({model:"claude-sonnet-4-20250514",max_tokens:1000,system:sys,
          messages:[...log.filter(m=>m.role==="user"||m.role==="ai").slice(-6).map(m=>({role:m.role==="user"?"user":"assistant",content:m.text})),{role:"user",content:q2}]})});
      const data = await res.json();
      setLog(l=>[...l,{role:"ai",text:data.content?.[0]?.text||"Try again."}]);
    } catch { setLog(l=>[...l,{role:"ai",text:"Connection issue — please try again."}]); }
    setLoading(false);
  };

  return (
    <div style={{display:"flex",flexDirection:"column",height:"calc(100vh - 120px)",minHeight:500}}>
      <PageHeader title="Ask CLaiMB" sub="Live AI assistant with full Coca-Cola NA marketing intelligence context"/>
      <div style={{flex:1,overflowY:"auto",paddingBottom:16}}>
        {log.map((m,i)=>(
          <div key={i} style={{display:"flex",justifyContent:m.role==="user"?"flex-end":"flex-start",marginBottom:12}}>
            {m.role==="ai"&&<div style={{width:28,height:28,minWidth:28,borderRadius:8,background:`linear-gradient(135deg,${C.teal},${C.violet})`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,color:"#fff",marginRight:8,marginTop:2,flexShrink:0}}>✦</div>}
            <div style={{maxWidth:"80%",padding:"12px 16px",borderRadius:m.role==="user"?"12px 12px 2px 12px":"12px 12px 12px 2px",
              background:m.role==="user"?C.violet:C.card2,border:m.role==="ai"?`1px solid ${C.border}`:"none",
              color:C.white,fontSize:12,lineHeight:1.7,whiteSpace:"pre-wrap",fontFamily:FF}}>
              {m.role==="ai"&&<div style={{fontSize:9,color:C.teal,fontWeight:700,marginBottom:5,letterSpacing:1}}>ASK CLaiMB</div>}
              {m.text}
            </div>
          </div>
        ))}
        {loading&&<div style={{display:"flex",marginBottom:12}}>
          <div style={{width:28,height:28,minWidth:28,borderRadius:8,background:`linear-gradient(135deg,${C.teal},${C.violet})`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,color:"#fff",marginRight:8,flexShrink:0}}>✦</div>
          <div style={{background:C.card2,border:`1px solid ${C.border}`,borderRadius:"12px 12px 12px 2px",padding:"12px 16px",color:C.teal,fontSize:12}}>Analyzing CCNA marketing AI data…</div>
        </div>}
        <div ref={ref}/>
      </div>
      <div style={{marginBottom:10}}>
        <div style={{fontSize:9,color:C.dim,letterSpacing:1,marginBottom:7}}>SUGGESTED QUESTIONS</div>
        <div style={{display:"flex",gap:7,flexWrap:"wrap"}}>
          {SAMPLES.map((s,i)=>(
            <button key={i} onClick={()=>send(s)} style={{background:C.card2,border:`1px solid ${C.border}`,
              borderRadius:16,color:C.off,padding:"4px 12px",cursor:"pointer",fontSize:11,fontFamily:FF}}>{s}</button>
          ))}
        </div>
      </div>
      <div style={{display:"flex",gap:10}}>
        <input value={q} onChange={e=>setQ(e.target.value)} onKeyDown={e=>e.key==="Enter"&&send()}
          placeholder="Ask about CCNA marketing AI transformation…"
          style={{flex:1,background:C.card,border:`1px solid ${C.border}`,borderRadius:8,color:C.white,
            padding:"12px 16px",fontSize:12,outline:"none",fontFamily:FF}}/>
        <button onClick={()=>send()} disabled={loading} style={{background:C.teal,border:"none",borderRadius:8,
          color:"#000",padding:"12px 20px",cursor:"pointer",fontWeight:700,fontSize:12,fontFamily:FF}}>
          {loading?"…":"Send"}
        </button>
      </div>
    </div>
  );
}

// ─── App ─────────────────────────────────────────────────────────────────────
function App() {
  const [page, setPage] = useState("dashboard");
  const [modal, setModal] = useState(null); // {adv, fn}
  const openAdvisory = (adv, fn) => { if (adv && fn) setModal({adv, fn}); };

  const renderPage = () => {
    switch(page) {
      case "dashboard":  return <Dashboard setPage={setPage} openAdvisory={openAdvisory}/>;
      case "functions":  return <FunctionsPage openAdvisory={openAdvisory}/>;
      case "findings":   return <FindingsPage openAdvisory={openAdvisory}/>;
      case "advisory":   return <AdvisoryPage openAdvisory={openAdvisory}/>;
      case "roi":        return <RoiPage/>;
      case "readiness":  return <ReadinessPage/>;
      case "ask":        return <AskPage/>;
      default:           return <Dashboard setPage={setPage} openAdvisory={openAdvisory}/>;
    }
  };

  return (
    <div style={{display:"flex",minHeight:"100vh",background:C.bg,fontFamily:FF,color:C.white}}>
      <Sidebar page={page} setPage={setPage}/>
      {/* Main */}
      <div style={{flex:1,overflowY:"auto"}}>
        {/* Top bar */}
        <div style={{background:C.sbg,borderBottom:`1px solid ${C.border}`,padding:"0 24px",
          display:"flex",alignItems:"center",justifyContent:"space-between",height:52,position:"sticky",top:0,zIndex:100}}>
          <div style={{fontSize:12,color:C.off}}>Coca-Cola North America · Marketing AI Intelligence</div>
          <div style={{display:"flex",alignItems:"center",gap:12}}>
            <div style={{fontSize:9,color:C.off,letterSpacing:1}}>AIMRI™</div>
            <div style={{fontSize:18,fontWeight:800,color:C.amber}}>3.24<span style={{fontSize:10,color:C.off}}>/5.0</span></div>
            <div style={{width:1,height:22,background:C.border}}/>
            <Pill text="CONFIDENTIAL" color={C.dim}/>
          </div>
        </div>
        {/* Content */}
        <div style={{padding:24,maxWidth:1040,margin:"0 auto"}}>
          {renderPage()}
        </div>
      </div>
      {/* Advisory Modal */}
      {modal && <AdvisoryModal adv={modal.adv} fn={modal.fn} onClose={()=>setModal(null)}/>}
    </div>
  );
}


const rootEl=document.getElementById('root');
ReactDOM.createRoot(rootEl).render(<App />);
