/* Mereka v2 — Analytics suite (Impact / Programme / Course / Experience / Expertise / Gig) */

/* ====== Shell ====== */
const ANALYTICS_NAV_TOP = [
  { label: 'Impact overview', icon: 'trending', to: '/app/analytics/impact' },
  { label: 'Programme', icon: 'bookmark', to: '/app/analytics/programme' },
  { label: 'Courses', icon: 'graduation', to: '/app/analytics/courses' },
  { label: 'Experience', icon: 'calendar', to: '/app/analytics/experience' },
  { label: 'Expertise', icon: 'award', to: '/app/analytics/expertise' },
  { label: 'Gig', icon: 'briefcase', to: '/app/analytics/gig' },
];
const ANALYTICS_NAV_BOT = [
  { label: 'Correlations', icon: 'layers', to: '/app/analytics/correlations' },
  { label: 'KPI builder', icon: 'spark', to: '/app/analytics/kpi' },
  { label: 'B40 impact', icon: 'user', to: '/app/analytics/b40' },
];

function AnalyticsShell({ active, back = '/app/dashboard/overview', children }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="flex">
        <aside className="hidden lg:block w-[220px] flex-shrink-0 px-5 py-6 bg-white border-r border-neutral-100 min-h-[calc(100vh-68px)]">
          <Link to={back} className="inline-flex items-center gap-2 text-sm text-neutral-700 hover:text-neutral-900 mb-6">
            <Icon name="chevronLeft" size={16} /> Back
          </Link>
          <h3 className="text-sm font-bold mb-3">Analytics</h3>
          <nav className="space-y-0.5 mb-6">
            {ANALYTICS_NAV_TOP.map(item => <ANavLink key={item.label} item={item} active={active === item.to || (active || '').startsWith(item.to + '/')} />)}
          </nav>
          <div className="border-t border-neutral-200 my-4" />
          <nav className="space-y-0.5">
            {ANALYTICS_NAV_BOT.map(item => <ANavLink key={item.label} item={item} active={active === item.to} />)}
          </nav>
        </aside>
        <main className="flex-1 min-w-0 py-8 px-4 lg:px-8 relative">
          {children}
          <button className="fixed bottom-6 right-6 z-30 inline-flex items-center gap-2 h-9 px-4 bg-neutral-900 text-white rounded-full text-sm font-medium shadow-lg hover:bg-neutral-800">
            <Icon name="filter" size={14} /> Filter
          </button>
        </main>
      </div>
    </div>
  );
}

function ANavLink({ item, active }) {
  return (
    <Link to={item.to}
      className={`flex items-center gap-3 px-3 h-9 rounded-lg text-sm transition-colors ${active ? 'bg-neutral-100 text-neutral-900 font-semibold' : 'text-neutral-700 hover:bg-neutral-50'}`}>
      <Icon name={item.icon} size={15} className={active ? 'text-neutral-900' : 'text-neutral-500'} />
      {item.label}
    </Link>
  );
}

/* ====== Shared bits ====== */
function APageHeader({ title, subtitle, action }) {
  return (
    <div className="flex items-start justify-between gap-4 mb-6 flex-wrap">
      <div>
        <h1 className="text-3xl font-bold">{title}</h1>
        {subtitle && <p className="text-sm text-neutral-500 mt-1">{subtitle}</p>}
      </div>
      {action}
    </div>
  );
}

function StatBox({ label, value, sub, delta, deltaTone = 'green' }) {
  const tones = { green: 'text-green-600', red: 'text-red-500' };
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-5">
      <p className="text-sm text-neutral-700 mb-1">{label}</p>
      <p className="text-3xl font-bold num-tabular">{value}</p>
      {(delta || sub) && (
        <p className="text-xs mt-1.5">
          {delta && <span className={tones[deltaTone]}>↗ {delta}</span>}
          {sub && <span className="text-neutral-500 ml-1">{sub}</span>}
        </p>
      )}
    </div>
  );
}

function ExportBtn({ label = 'Export' }) {
  return (
    <button className="inline-flex items-center gap-2 h-10 px-4 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">
      <Icon name="download" size={14} /> {label}
    </button>
  );
}

function SearchBox({ placeholder, className = '' }) {
  return (
    <div className={`relative ${className}`}>
      <Icon name="search" size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400" />
      <input placeholder={placeholder} className="w-full h-10 pl-9 pr-3 text-sm border border-neutral-200 rounded-lg bg-white focus:outline-none focus:border-neutral-400" />
    </div>
  );
}

const AFILTER_OPTIONS = {
  programme: ['All programmes', 'AI4U', 'AI Fluency by Microsoft', 'AI First Designer School', 'Explore Generative AI', 'Get Started with Microsoft Copilot'],
  cohort: ['All cohorts', 'Cohort APR 2026', 'Cohort MAR 2026', 'Cohort FEB 2026', 'Cohort JAN 2026'],
  category: ['All categories', 'AI & ML', 'Design', 'Data', 'Product', 'Dev', 'Marketing'],
  instructor: ['All instructors', 'Chris Wales', 'Jason Brown', 'Alex Chen', 'Sophia Chen', 'Liam Smith'],
  course: ['All courses', 'Gen AI Fundamentals', 'UX Research Masterclass', 'Python for Data', 'Responsible AI Ethics'],
  experience: ['All experiences', 'AI in Everyday Life Talk', 'Generative AI Workshop', 'Responsible AI Forum'],
  type: ['All types', 'Events', 'Workshops', 'Talks', 'Shows & Exhibitions'],
  status: ['All', 'Open', 'In progress', 'Closed'],
  results: ['All records', 'Program-linked', 'Standalone'],
};
function aFilterOptionsFor(label) {
  const l = (label || '').toLowerCase();
  if (l.includes('result')) return { type: 'radio', options: AFILTER_OPTIONS.results };
  if (l.includes('cohort')) return { type: 'multi', options: AFILTER_OPTIONS.cohort };
  if (l.includes('categor')) return { type: 'multi', options: AFILTER_OPTIONS.category };
  if (l.includes('instructor')) return { type: 'multi', options: AFILTER_OPTIONS.instructor };
  if (l.includes('course')) return { type: 'multi', options: AFILTER_OPTIONS.course };
  if (l.includes('experience type')) return { type: 'multi', options: AFILTER_OPTIONS.type };
  if (l.includes('experience')) return { type: 'multi', options: AFILTER_OPTIONS.experience };
  if (l.includes('status')) return { type: 'multi', options: AFILTER_OPTIONS.status };
  return { type: 'multi', options: AFILTER_OPTIONS.programme };
}

function AFilterPopover({ label }) {
  const { type, options } = aFilterOptionsFor(label);
  const [sel, setSel] = useState(type === 'radio' ? options[0] : options.slice(1));
  if (type === 'radio') {
    return (
      <div className="absolute left-0 top-[calc(100%+6px)] w-[300px] bg-white rounded-2xl border border-neutral-100 z-40" style={{ boxShadow: '0 16px 44px rgba(0,0,0,0.14)' }} onClick={e => e.stopPropagation()}>
        <div className="flex items-center gap-2.5 px-4 h-12 border-b border-neutral-100">
          <Icon name="search" size={16} className="text-neutral-400" />
          <input placeholder="Search programmes..." className="flex-1 text-sm focus:outline-none bg-transparent" />
        </div>
        <div className="py-2">
          {options.map(o => (
            <button key={o} onClick={() => setSel(o)} className="w-full flex items-center gap-3 px-4 py-3 hover:bg-neutral-50 text-left">
              <span className={`w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 ${sel === o ? 'border-[6px] border-neutral-900' : 'border-2 border-neutral-300'}`} />
              <span className="text-[15px] text-neutral-800">{o}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }
  const toggle = (o) => setSel(s => s.includes(o) ? s.filter(x => x !== o) : [...s, o]);
  return (
    <div className="absolute left-0 top-[calc(100%+6px)] w-[320px] bg-white rounded-2xl border border-neutral-100 z-40" style={{ boxShadow: '0 16px 44px rgba(0,0,0,0.14)' }} onClick={e => e.stopPropagation()}>
      <div className="flex items-center gap-2.5 px-4 h-12 border-b border-neutral-100">
        <Icon name="search" size={16} className="text-neutral-400" />
        <input placeholder="Search programmes..." className="flex-1 text-sm focus:outline-none bg-transparent" />
      </div>
      <div className="py-2 max-h-[260px] overflow-y-auto">
        {options.map(o => {
          const on = sel.includes(o);
          return (
            <button key={o} onClick={() => toggle(o)} className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-neutral-50 text-left">
              <span className={`w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0 ${on ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>{on && <Icon name="check" size={14} strokeWidth={3} />}</span>
              <span className="text-[15px] text-neutral-800">{o}</span>
            </button>
          );
        })}
      </div>
      <div className="flex items-center justify-end gap-3 px-4 py-3 border-t border-neutral-100">
        <button onClick={() => setSel([])} className="text-[14px] text-neutral-600 hover:text-neutral-900">Clear filter</button>
        <button className="h-9 px-5 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">Apply filter</button>
      </div>
    </div>
  );
}

function FilterRow({ items, resetable = true }) {
  const [open, setOpen] = useState(null);
  const ref = useRef(null);
  useEffect(() => {
    if (open === null) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(null); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, [open]);
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-4 mb-6" ref={ref}>
      <div className="flex items-center gap-2 mb-3 text-sm text-neutral-700"><Icon name="filter" size={14} /> Filters:</div>
      <div className="grid gap-3" style={{ gridTemplateColumns: `repeat(${items.length},1fr) auto` }}>
        {items.map((it, i) => (
          <div key={i} className="relative">
            <p className="text-sm mb-1.5 flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full" style={{ background: it.dot || '#22C55E' }} />{it.label}</p>
            <button onClick={e => { e.stopPropagation(); setOpen(open === i ? null : i); }}
              className={`w-full h-10 border rounded-lg px-3 flex items-center justify-between text-sm bg-white transition-colors ${open === i ? 'border-neutral-400' : 'border-neutral-200 hover:border-neutral-300'}`}>
              <span className="flex items-center gap-2">{it.value} {it.count != null && <span className="px-1.5 py-0.5 bg-neutral-100 text-xs rounded">{it.count}</span>}</span>
              <Icon name="chevronDown" size={12} className={`text-neutral-500 transition-transform ${open === i ? 'rotate-180' : ''}`} />
            </button>
            {open === i && <AFilterPopover label={it.label} />}
          </div>
        ))}
        {resetable && <div className="self-end"><button className="text-blue-500 text-xs font-medium hover:underline inline-flex items-center gap-1 h-10"><Icon name="refresh" size={12} /> Reset</button></div>}
      </div>
    </div>
  );
}

function KeyInsightCard({ title = 'KEY INSIGHT', body }) {
  return (
    <div className="bg-blue-50/40 border border-blue-200 rounded-xl p-4">
      <div className="flex items-center justify-between mb-1.5">
        <p className="text-xs font-bold text-neutral-700 inline-flex items-center gap-1.5"><span>💡</span> {title}</p>
        <Icon name="arrowUpRight" size={12} className="text-neutral-400" />
      </div>
      <p className="text-xs text-neutral-700 leading-relaxed">{body}</p>
    </div>
  );
}

function HBar({ label, value, max, color = '#22C55E', delta }) {
  const pct = Math.min(100, (value / max) * 100);
  const trackColor = color + '33';
  return (
    <div className="grid grid-cols-1 lg:grid-cols-[100px_1fr_60px_50px] items-center gap-3 text-xs mb-2.5">
      <span className="text-neutral-700">{label}</span>
      <div className="h-3 rounded-full overflow-hidden" style={{ background: trackColor }}>
        <div className="h-full rounded-full" style={{ width: pct + '%', background: color }} />
      </div>
      <span className="font-semibold num-tabular">{typeof value === 'number' ? value.toLocaleString() : value}</span>
      <span className={`text-right ${delta && delta.startsWith('-') ? 'text-red-500' : 'text-neutral-500'}`}>{delta}</span>
    </div>
  );
}

function FeedbackBlock({ avg = 4.3, count = 284, hue = 45, quotes = [] }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-6 mt-6">
      <h3 className="font-bold mb-5">Feedback</h3>
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_2fr] gap-8">
        <div>
          <p className="text-sm text-neutral-500 mb-2">Average Rating</p>
          <div className="text-5xl font-bold mb-2">{avg}</div>
          <div className="flex items-center gap-0.5 mb-3">
            {[0, 1, 2, 3, 4].map(i => <Icon key={i} name="star" size={14} fill="#FBBF24" strokeWidth={0} />)}
          </div>
          <p className="text-xs text-neutral-500">From {count} attendees</p>
          <div className="mt-4 flex flex-wrap gap-2">
            {['community (13)', 'engaging (11)', 'insightful (5)', 'skills (4)'].map(c => (
              <span key={c} className="px-3 h-7 inline-flex items-center bg-neutral-100 text-neutral-700 text-xs rounded-full">{c}</span>
            ))}
          </div>
        </div>
        <div>
          <div className="space-y-1">
            {[[5, 65], [4, 24], [3, 7], [2, 3], [1, 1]].map(([n, p]) => (
              <div key={n} className="grid grid-cols-1 lg:grid-cols-[20px_1fr_40px] items-center gap-3 text-xs">
                <span>{n}</span>
                <div className="h-2.5 bg-neutral-100 rounded-full overflow-hidden"><div className="h-full" style={{ background: `oklch(0.75 0.16 ${hue})`, width: p + '%' }} /></div>
                <span className="text-right text-neutral-500 num-tabular">{p}%</span>
              </div>
            ))}
          </div>
          <div className="mt-6 space-y-3">
            {quotes.length === 0 ? (
              <>
                <Quote>"Finally an AI event that takes ethics seriously. The regulation panel was thought-provoking."</Quote>
                <Quote>"Would have liked more practical frameworks for implementing responsible AI in companies."</Quote>
              </>
            ) : quotes.map((q, i) => <Quote key={i}>{q}</Quote>)}
          </div>
        </div>
      </div>
    </div>
  );
}

function Quote({ children }) {
  return (
    <div>
      <p className="text-sm text-neutral-700 italic">{children}</p>
      <p className="text-xs text-neutral-500 mt-1 inline-flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-amber-400" /> Policy Researcher</p>
    </div>
  );
}

/* =================================================================
   IMPACT OVERVIEW
   ================================================================= */
const IMPACT_BY_HUB = [
  { members: '12,847', revenue: 'RM 3.6M', completion: '66%', employment: '4.33%', placements: '4,218 placements',
    progOnly: '8,731', both: '3,281', expOnly: '766', bothPct: '16.3% of Programme',
    bar: [{ n: '10,753', w: '74%' }, { n: '2,094', w: '17%' }, { n: '753', w: '9%' }] },
  { members: '5,392', revenue: 'RM 1.4M', completion: '72%', employment: '6.1%', placements: '1,840 placements',
    progOnly: '3,560', both: '1,120', expOnly: '302', bothPct: '21.0% of Programme',
    bar: [{ n: '4,210', w: '72%' }, { n: '980', w: '18%' }, { n: '410', w: '10%' }] },
  { members: '1,128', revenue: 'RM 720K', completion: '81%', employment: '9.4%', placements: '640 placements',
    progOnly: '740', both: '240', expOnly: '72', bothPct: '24.5% of Programme',
    bar: [{ n: '920', w: '70%' }, { n: '210', w: '18%' }, { n: '86', w: '12%' }] },
];

function AnalyticsImpactOverviewPage() {
  const M = IMPACT_BY_HUB[hubIdx(useHub())] || IMPACT_BY_HUB[0];
  return (
    <AnalyticsShell active="/app/analytics/impact">
      <APageHeader title="Impact Overview" subtitle="Cross-service performance and impact metrics at a glance."
        action={
          <div className="flex items-center gap-2">
            <button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium inline-flex items-center gap-2 bg-white hover:bg-neutral-50"><Icon name="chat" size={14} /> Customize</button>
            <button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium inline-flex items-center gap-2 bg-white hover:bg-neutral-50"><Icon name="calendar" size={14} /> Last 3 months <Icon name="chevronDown" size={12} /></button>
            <ExportBtn />
          </div>
        }
      />

      <h2 className="text-xl font-bold mb-4">Overview</h2>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-10">
        <StatBox label="Total Active Members" value={M.members} delta="+12.4%" sub="vs last period" />
        <StatBox label="Total Revenue" value={M.revenue} delta="+18.2%" sub="Programmes + Exp + Gigs" />
        <StatBox label="Completion Rate" value={<>{M.completion} <span className="text-xs align-middle ml-1 px-2 py-0.5 bg-blue-100 text-blue-600 rounded font-semibold">ON TRACK</span></>} delta="+3.1%" sub="Across programmes" />
        <StatBox label="Employment Outcome" value={M.employment} delta="+0.8%" sub={M.placements} />
      </div>

      {/* Cross-service impact analyser */}
      <div className="flex items-start justify-between mb-3">
        <div>
          <h2 className="text-xl font-bold">Cross-Service Impact Analyser</h2>
          <p className="text-sm text-neutral-500 mt-0.5">See how members who engaged with X services perform across Y services</p>
        </div>
        <ExportBtn />
      </div>
      <div className="bg-white border border-neutral-200 rounded-2xl p-5 mb-6">
        <p className="text-xs font-bold text-neutral-500 mb-2">1 - TARGET GROUP</p>
        <div className="flex items-center gap-2 mb-5">
          <button className="px-4 h-9 bg-neutral-900 text-white rounded-full text-sm font-semibold">All segments</button>
          <button className="px-4 h-9 border border-neutral-300 rounded-full text-sm bg-white">B40 only</button>
          <button className="px-4 h-9 border border-neutral-300 rounded-full text-sm bg-white">Non-members (PDRM)</button>
        </div>
        <p className="text-xs font-bold text-neutral-500 mb-2">2 - SERVICE TYPE (select 2 to compare)</p>
        <div className="flex items-center gap-3 mb-5">
          <span className="text-sm text-neutral-700">Compare</span>
          <div className="h-10 px-3 border border-neutral-200 rounded-lg flex items-center gap-2 text-sm">
            <span className="w-1.5 h-1.5 rounded-full bg-green-500" /> Programmes <span className="px-1.5 py-0.5 bg-neutral-100 text-xs rounded">12</span>
            <Icon name="chevronDown" size={12} className="text-neutral-500" />
          </div>
          <span className="text-neutral-500 font-bold">&</span>
          <div className="h-10 px-3 border border-neutral-200 rounded-lg flex items-center gap-2 text-sm">
            <span className="w-1.5 h-1.5 rounded-full bg-amber-500" /> Experiences <span className="px-1.5 py-0.5 bg-neutral-100 text-xs rounded">8</span>
            <Icon name="chevronDown" size={12} className="text-neutral-500" />
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-5">
          <div>
            {/* Stacked bar */}
            <div className="flex h-8 rounded overflow-hidden mb-3">
              <div className="bg-green-500 text-white text-xs flex items-center justify-center font-semibold" style={{ width: M.bar[0].w }}>{M.bar[0].n}</div>
              <div className="bg-blue-500 text-white text-xs flex items-center justify-center font-semibold" style={{ width: M.bar[1].w }}>{M.bar[1].n}</div>
              <div className="bg-amber-400 text-white text-xs flex items-center justify-center font-semibold" style={{ width: M.bar[2].w }}>{M.bar[2].n}</div>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 mb-5">
              <div className="border border-neutral-200 rounded-xl p-4 text-center">
                <p className="font-bold text-lg">{M.progOnly} <span className="text-xs font-normal">members</span></p>
                <p className="text-xs text-neutral-500">in programme only</p>
              </div>
              <div className="border-2 border-blue-500 bg-blue-50/40 rounded-xl p-4 text-center">
                <p className="font-bold text-lg">{M.both} <span className="text-xs font-normal">members</span></p>
                <p className="text-xs text-neutral-500">In both</p>
                <p className="text-xs text-neutral-600 mt-0.5">{M.bothPct}</p>
              </div>
              <div className="border border-neutral-200 rounded-xl p-4 text-center">
                <p className="font-bold text-lg">{M.expOnly} <span className="text-xs font-normal">members</span></p>
                <p className="text-xs text-neutral-500">in experiences only</p>
              </div>
            </div>

            <div className="border border-neutral-200 rounded-xl overflow-hidden">
              <p className="px-4 py-2.5 text-sm font-semibold border-b border-neutral-100">Top performing service combinations</p>
              {[
                ['Explore Generative AI', 'Generative AI Works…', 148, 'HIGH'],
                ['AI4U', 'AI in Everyday Life Talk', 94, 'HIGH'],
                ['AI First Designer Sch…', 'Digital Future Expo', 32, 'MID'],
                ['AI First Designer Sch…', 'Digital Future Expo', 32, 'MID'],
              ].map((r, i) => (
                <div key={i} className="grid grid-cols-1 lg:grid-cols-[30px_1fr_auto_1fr_auto_50px] items-center gap-2 px-4 py-2.5 border-t border-neutral-100 text-xs">
                  <span>{i + 1}</span>
                  <span className="px-2 py-1 border border-neutral-200 rounded bg-white inline-flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-green-500" /> {r[0]}</span>
                  <span className="text-neutral-400">&amp;</span>
                  <span className="px-2 py-1 border border-neutral-200 rounded bg-white inline-flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-amber-500" /> {r[1]}</span>
                  <span className="text-neutral-700">{r[2]} overlapping members</span>
                  <span className={`text-right font-bold ${r[3] === 'HIGH' ? 'text-green-600' : 'text-amber-500'}`}>{r[3]}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="space-y-3">
            <LiftCard title="Completion Lift" value="+41%" sub="vs single-service" />
            <LiftCard title="Employment Lift" value="+20%" sub="within 90 days" />
            <LiftCard title="NPS Improvement" value="+12 pts" sub="satisfaction score" />
            <LiftCard title="Revenue Impact" value="+RM 850K" sub="combined uplift" />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-12">
        {Array.from({ length: 3 }, (_, i) => (
          <KeyInsightCard key={i} body="Members enrolled in both Programmes and Experiences show 41% higher completion rates and 28% better employment outcomes. Experiences reinforce Programme learning and create stronger career pathways." />
        ))}
      </div>

      {/* Service Overview */}
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-xl font-bold">Service Overview</h2>
        <ExportBtn />
      </div>
      <div className="space-y-3 mb-10">
        <ServiceRow color="#22C55E" title="Programmes" count="12" desc="Cohort-based learning tracks" stats={[['14', 'Active'], ['66% (8479)', 'Completion'], ['RM 1.2M', 'Revenue']]} />
        <ServiceRow color="#EC4899" title="Courses" count="28" desc="Self-paced modules, shared across programmes" stats={[['4,218', 'Enrolled'], ['72% (3037)', 'Completion'], ['RM 248K', 'Revenue']]} />
        <ServiceRow color="#F59E0B" title="Experiences" count="28" desc="Events, workshops, talks, shows" stats={[['2,847', 'Attendees'], ['4.3 ★', 'Avg Rating'], ['RM 528K', 'Revenue']]} />
        <ServiceRow color="#06B6D4" title="All expertise" count="1,247" desc="Expert hourly bookings" stats={[['892', 'Bookings'], ['4.3 ★', 'Avg Rating'], ['RM 358K', 'Revenue']]} />
        <ServiceRow color="#A855F7" title="All gigs" count="322" desc="Project-based freelance work" stats={[['306', 'Open'], ['1,203', 'Completed'], ['RM 1.8M', 'Revenue']]} />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-10">
        <KeyInsightCard title="KEY INSIGHT" body={<>Programme completers are 3.2× more likely to secure a Gig within 60 days <span className="block mt-1 text-neutral-500">Based on 1,247 matched members across AI4U and Explore Generative AI cohorts</span></>} />
        <KeyInsightCard title="KEY INSIGHT" body={<>B40 members who attend Experiences show 41% higher completion rates <span className="block mt-1 text-neutral-500">Compared to B40 members who enrol in Programmes alone → 4,218 members analysed</span></>} />
        <KeyInsightCard title="KEY INSIGHT" body={<>Expertise bookings drive 2.1× higher income uplift for freelancers <span className="block mt-1 text-neutral-500">Median income increase of RM 1,850/month within 3 months of first booking</span></>} />
      </div>

      {/* Recent Activity + Top Locations */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-10">
        <div className="bg-white border border-neutral-200 rounded-2xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-bold">Recent Activity</h3>
            <button className="h-8 px-3 border border-neutral-300 rounded-lg text-xs font-medium hover:bg-neutral-50">View All</button>
          </div>
          <div className="space-y-3">
            {[
              ['FJ', '#FBBF24', 'Florence Jones', 'completed AI4U Programme Module 5', '2m ago · AI4U cohort APR 2026', 'Program', 'blue'],
              ['NA', '#A78BFA', 'Natalie Andrew', 'booked an Expertise session with Chris Wales', '2m ago · UX Design · RM 180/hr', 'Program', 'blue'],
              ['JT', '#F87171', 'James Thompson', 'posted a new Gig: UX Research Specialist', '4h ago · Design · RM 3,800 180/hr', 'Standalone', 'gray'],
              ['CM', '#34D399', 'Carla Mendoza', 'attended AI Fluency Experience', '5h ago · AI Fluency Experience', 'Program', 'blue'],
              ['OH', '#FB923C', 'Oliver Hayes', 'enrolled in Explore Generative AI', '5h ago · Explore Generative AI', 'Program', 'blue'],
              ['JK', '#F472B6', 'Jessica Kim', 'completed the Advanced UX Design course', '7h ago · Advanced UX Design', 'Program', 'blue'],
            ].map(([initials, color, name, action, meta, tag, tagTone], i) => (
              <div key={i} className="flex items-start gap-3">
                <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: color }}>{initials}</div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm"><span className="font-bold">{name}</span> <span className="text-neutral-600">{action}</span></p>
                  <p className="text-xs text-neutral-500 mt-0.5">{meta}</p>
                </div>
                <span className={`px-3 h-6 inline-flex items-center text-xs font-medium rounded ${tagTone === 'blue' ? 'bg-blue-50 text-blue-600' : 'bg-neutral-100 text-neutral-600'}`}>{tag}</span>
              </div>
            ))}
          </div>
        </div>

        <TopLocations />
      </div>

      {/* Revenue Trend */}
      <div className="bg-white border border-neutral-200 rounded-2xl p-5 mb-12">
        <h3 className="font-bold mb-1">Revenue Trend</h3>
        <p className="text-sm text-neutral-500 mb-5">Monthly revenue across all service pillars</p>
        <div className="flex items-center gap-5 mb-4 flex-wrap text-xs">
          {[
            ['Programmes', '#22C55E'], ['Courses', '#F59E0B'], ['Experiences', '#06B6D4'],
            ['Expertise', '#A855F7'], ['Gigs', '#F59E0B'],
          ].map(([l, c]) => (
            <span key={l} className="inline-flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full" style={{ background: c }} />{l}</span>
          ))}
        </div>
        <RevenueTrendChart />
      </div>
    </AnalyticsShell>
  );
}

function LiftCard({ title, value, sub }) {
  return (
    <div className="border border-neutral-200 rounded-xl px-4 py-3">
      <p className="text-xs text-neutral-500">{title}</p>
      <p className="text-2xl font-bold mt-0.5">{value}</p>
      <p className="text-xs text-neutral-500 mt-0.5">{sub}</p>
    </div>
  );
}

function ServiceRow({ color, title, count, desc, stats }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl px-5 py-4 grid grid-cols-1 lg:grid-cols-[1fr_auto_auto_auto_24px] items-center gap-6">
      <div>
        <p className="font-semibold inline-flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full" style={{ background: color }} /> {title} <span className="px-1.5 py-0.5 bg-neutral-100 text-xs rounded text-neutral-600 font-medium">{count}</span> <span className="font-normal text-xs text-neutral-500 ml-1">{desc}</span></p>
      </div>
      {stats.map(([v, l], i) => (
        <div key={i} className="text-right min-w-[100px]">
          <p className="font-bold text-base num-tabular">{v}</p>
          <p className="text-xs text-neutral-500">{l}</p>
        </div>
      ))}
      <Icon name="arrowUpRight" size={14} className="text-neutral-400" />
    </div>
  );
}

const TOP_LOCATIONS = [
  ['Kuala Lumpur', 51, 1663, '🇲🇾'],
  ['Selangor', 24, 800, '🇲🇾'],
  ['Negeri Sembilan', 10, 306, '🇲🇾'],
  ['Penang', 7, 214, '🇲🇾'],
  ['Johor Bahru', 5, 152, '🇲🇾'],
];

function TopLocations({ title = 'Top Locations' }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-bold">{title}</h3>
        <button className="h-8 px-3 border border-neutral-300 rounded-lg text-xs font-medium hover:bg-neutral-50">View All</button>
      </div>
      <div className="space-y-3">
        {TOP_LOCATIONS.map(([name, pct, n, flag]) => (
          <div key={name} className="grid grid-cols-1 lg:grid-cols-[24px_140px_1fr_60px_50px] items-center gap-3 text-xs">
            <span className="text-base">{flag}</span>
            <span className="text-neutral-700">{name}</span>
            <div className="h-2.5 bg-neutral-100 rounded-full overflow-hidden"><div className="h-full bg-neutral-900 rounded-full" style={{ width: pct + '%' }} /></div>
            <span className="text-right num-tabular text-neutral-500">{pct}%</span>
            <span className="text-right text-blue-500 font-medium num-tabular">{n.toLocaleString()}</span>
          </div>
        ))}
      </div>
      <p className="text-xs text-neutral-500 mt-3">+7 more locations</p>
    </div>
  );
}

function RevenueTrendChart() {
  const months = ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr'];
  const series = [
    { color: '#A855F7', vals: [200, 220, 250, 270, 310, 340, 390] },
    { color: '#22C55E', vals: [180, 200, 230, 250, 280, 310, 350] },
    { color: '#06B6D4', vals: [140, 150, 170, 180, 200, 220, 250] },
    { color: '#F59E0B', vals: [100, 120, 130, 140, 150, 160, 170] },
  ];
  const w = 800, h = 240, pad = 30;
  const max = 400;
  const xStep = (w - pad * 2) / (months.length - 1);
  return (
    <svg viewBox={`0 0 ${w} ${h + 30}`} className="w-full">
      {[400, 350, 300, 250, 200, 150, 100, 50].map((v, i) => {
        const y = pad + (i * (h - pad * 2)) / 7;
        return <g key={v}>
          <text x={4} y={y + 4} fontSize={10} fill="#9CA3AF">RM {v}K</text>
        </g>;
      })}
      {series.map((s, si) => {
        const points = s.vals.map((v, i) => [pad + i * xStep, h - pad - ((v / max) * (h - pad * 2))]);
        const path = points.map((p, i) => (i ? 'L' : 'M') + p.join(',')).join(' ');
        const area = path + ` L${points[points.length - 1][0]},${h - pad} L${points[0][0]},${h - pad} Z`;
        return (
          <g key={si}>
            <path d={area} fill={s.color} opacity={0.08} />
            <path d={path} stroke={s.color} strokeWidth={2} fill="none" />
            {points.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r={3} fill={s.color} />)}
          </g>
        );
      })}
      {months.map((m, i) => (
        <text key={m} x={pad + i * xStep} y={h + 15} textAnchor="middle" fontSize={11} fill="#6B7280">{m}</text>
      ))}
    </svg>
  );
}

Object.assign(window, {
  AnalyticsImpactOverviewPage,
  AnalyticsShell, APageHeader, StatBox, ExportBtn, SearchBox, FilterRow,
  KeyInsightCard, HBar, FeedbackBlock, TopLocations,
});
