/* Mereka v2 — Program admin suite: shared shell + Overview / Dashboard / Feedback
   Figma: 5208-21569, 19636, 20567, 23213, 22571, 74459 */

/* ============ Shared program shell (rail + 2-level sidebar) ============ */
const PROG_RAIL = [
  { id: 'p1', hue: 340, active: true },
  { id: 'p2', hue: 220 },
  { id: 'p3', hue: 25 },
];

/* Simplified IA from Figma 5289 (Programme — Admin): Community / Learning / Admin */
const PROG_NAV = [
  { group: 'Community', items: [
    { key: 'feed', label: 'Feed', icon: 'document', to: '/app/program/admin/feed' },
    { key: 'members', label: 'Members', icon: 'user', to: '/app/program/admin/members' },
  ]},
  { group: 'Learning', items: [
    { key: 'overview', label: 'Overview', icon: 'eye', to: '/app/program/admin/overview' },
  ]},
  { group: 'Admin', items: [
    { key: 'dashboard', label: 'Analytics', icon: 'barChart', to: '/app/program/admin/dashboard' },
    { key: 'manage-members', label: 'Manage Members', icon: 'userPlus', to: '/app/program/admin/members' },
    { key: 'settings', label: 'Programme Settings', icon: 'settings', to: '/app/program/admin/settings' },
    { key: 'feedback', label: 'Programme Feedback', icon: 'star', to: '/app/program/admin/feedback' },
  ]},
];

const CURRICULUM_SUB = [
  { key: 'material', label: 'Course Material', icon: 'document', to: '/app/program/admin/curriculum', badge: true },
  { key: 'forum', label: 'Forum', icon: 'chat', to: '/app/program/admin/curriculum/forum' },
  { key: 'notes', label: 'Student notes', icon: 'edit' },
  { key: 'test', label: 'Test', icon: 'clipboard', to: '/app/program/admin/curriculum/test' },
  { key: 'submission', label: 'Submission', icon: 'document', to: '/app/program/admin/curriculum/submission' },
];

function ProgramRail({ single }) {
  return (
    <aside className="hidden lg:flex w-[64px] bg-neutral-50 border-r border-neutral-200 flex-col items-center py-4 gap-3 flex-shrink-0 min-h-[calc(100vh-80px)]">
      <Link to="/app/program/manage" className="w-9 h-9 rounded-full bg-white border border-neutral-200 flex items-center justify-center hover:bg-neutral-100 text-neutral-600">
        <Icon name="chevronLeft" size={16} />
      </Link>
      <div className="flex flex-col items-center gap-2 mt-2">
        {(single ? PROG_RAIL.slice(0, 1) : PROG_RAIL).map(p => (
          <button key={p.id} className={`relative w-11 h-11 rounded-2xl overflow-hidden border-2 ${p.active ? 'border-neutral-900' : 'border-transparent'}`}>
            {p.active && !single && <span className="absolute -left-[6px] top-1/2 -translate-y-1/2 w-1 h-5 rounded-full bg-blue-500" />}
            <div className="w-full h-full" style={{ background: `linear-gradient(135deg, oklch(0.86 0.13 ${p.hue}), oklch(0.72 0.18 ${p.hue + 30}))` }} />
          </button>
        ))}
      </div>
      {!single && (
        <button className="w-11 h-11 rounded-2xl bg-white border border-dashed border-neutral-300 flex items-center justify-center text-neutral-500 hover:bg-neutral-100">
          <Icon name="plus" size={16} />
        </button>
      )}
      <button className="w-11 h-11 rounded-2xl flex items-center justify-center text-neutral-500 hover:bg-neutral-100 mt-1">
        <Icon name="settings" size={18} />
      </button>
    </aside>
  );
}

function ProgramSideNav({ active }) {
  const prog = useProg();
  const [collapsed, setCollapsed] = useState({});
  const [swOpen, setSwOpen] = useState(false);
  const swRef = useRef(null);
  useEffect(() => {
    if (!swOpen) return;
    const h = (e) => { if (swRef.current && !swRef.current.contains(e.target)) setSwOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [swOpen]);
  const progList = (typeof MHP_ROWS !== 'undefined' ? MHP_ROWS : []);
  const progHue = (n) => { let h = 0; for (let i = 0; i < String(n).length; i++) h = (h + String(n).charCodeAt(i) * 7) % 360; return h; };
  return (
    <aside className="hidden lg:block w-[256px] bg-white border-r border-neutral-200 flex-shrink-0 py-5 px-3 min-h-[calc(100vh-80px)]">
      <Link to="/app/dashboard/programmes" className="flex items-center gap-2 text-sm text-neutral-500 hover:text-neutral-800 px-2 mb-5">
        <Icon name="chevronLeft" size={16} /> Back to main dashboard
      </Link>
      <p className="text-[12px] font-semibold text-neutral-400 px-2 mb-1.5 uppercase tracking-wide">Switch programme</p>
      <div className="relative mb-5" ref={swRef}>
        <button onClick={() => setSwOpen(o => !o)} aria-haspopup="listbox" aria-expanded={swOpen}
          className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl border transition-colors ${swOpen ? 'border-neutral-300 bg-neutral-50' : 'border-neutral-200 hover:bg-neutral-50'}`}>
          <span className="w-7 h-7 rounded-lg flex-shrink-0 flex items-center justify-center text-white" style={{ background: `linear-gradient(135deg, oklch(0.72 0.16 ${progHue(prog.name)}), oklch(0.55 0.2 ${(progHue(prog.name) + 40) % 360}))` }}>
            <Icon name="spark" size={14} />
          </span>
          <span className="flex-1 text-left text-sm font-semibold text-neutral-900 truncate">{prog.name}</span>
          <Icon name="chevronDown" size={16} className={`text-neutral-400 flex-shrink-0 transition-transform ${swOpen ? 'rotate-180' : ''}`} />
        </button>
        {swOpen && (
          <div className="absolute left-0 right-0 top-[calc(100%+6px)] z-40 bg-white border border-neutral-200 rounded-xl py-1.5 max-h-[360px] overflow-y-auto scrollbar-thin" style={{ boxShadow: '0 16px 40px rgba(0,0,0,0.16)' }} role="listbox">
            <p className="px-3 pt-1 pb-1.5 text-[11px] font-bold uppercase tracking-wide text-neutral-400">Your programmes</p>
            {progList.map((p) => {
              const activeItem = p.name === prog.name;
              return (
                <button key={p.name} role="option" aria-selected={activeItem}
                  onClick={() => { setProg(p); setSwOpen(false); }}
                  className="w-full flex items-center gap-2.5 px-3 py-2 text-left hover:bg-neutral-50 transition-colors">
                  <span className="w-7 h-7 rounded-lg flex-shrink-0 flex items-center justify-center text-white" style={{ background: `linear-gradient(135deg, oklch(0.72 0.16 ${progHue(p.name)}), oklch(0.55 0.2 ${(progHue(p.name) + 40) % 360}))` }}>
                    <Icon name="spark" size={13} />
                  </span>
                  <span className="flex-1 min-w-0">
                    <span className="block text-[13px] font-semibold text-neutral-900 truncate">{p.name}</span>
                    <span className="block text-[11px] text-neutral-500 truncate">{p.owner}</span>
                  </span>
                  {activeItem && <Icon name="check" size={15} strokeWidth={2.5} className="text-blue-600 flex-shrink-0" />}
                </button>
              );
            })}
          </div>
        )}
      </div>
      {PROG_NAV.map(g => {
        const isCol = collapsed[g.group];
        return (
          <div key={g.group} className="mb-3">
            <button onClick={() => setCollapsed(c => ({ ...c, [g.group]: !c[g.group] }))}
              className="w-full flex items-center justify-between px-2 mb-1.5 group">
              <span className="text-[13px] font-bold text-neutral-900">{g.group}</span>
              <Icon name={isCol ? 'chevronDown' : 'chevronUp'} size={14} className="text-neutral-400 group-hover:text-neutral-700" />
            </button>
            {!isCol && (
              <div className="space-y-0.5">
                {g.items.map(item => {
                  const isActive = active === item.key;
                  const cls = `w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${isActive ? 'bg-neutral-100 text-neutral-900 font-semibold' : (item.to ? 'text-neutral-700 hover:bg-neutral-50' : 'text-neutral-400')}`;
                  const inner = (
                    <>
                      <Icon name={item.icon} size={16} className={isActive ? 'text-neutral-900' : (item.to ? 'text-neutral-500' : 'text-neutral-300')} />
                      <span className="flex-1 text-left">{item.label}</span>
                      {item.badge && <span className="w-1.5 h-1.5 rounded-full bg-blue-500" />}
                    </>
                  );
                  return item.to
                    ? <Link key={item.key} to={item.to} className={cls}>{inner}</Link>
                    : <button key={item.key} className={cls}>{inner}</button>;
                })}
              </div>
            )}
          </div>
        );
      })}
    </aside>
  );
}

function CurriculumSubNav({ active }) {
  return (
    <aside className="hidden lg:block w-[210px] bg-white border-r border-neutral-200 flex-shrink-0 py-6 px-3 min-h-[calc(100vh-80px)]">
      <h3 className="text-sm font-bold text-neutral-900 mb-3 px-3">Curriculum</h3>
      <div className="space-y-0.5">
        {CURRICULUM_SUB.map(item => {
          const isActive = active === item.key;
          const cls = `w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${isActive ? 'bg-neutral-100 text-neutral-900 font-semibold' : (item.to ? 'text-neutral-700 hover:bg-neutral-50' : 'text-neutral-400')}`;
          const inner = (
            <>
              <Icon name={item.icon} size={16} className={isActive ? 'text-neutral-900' : (item.to ? 'text-neutral-500' : 'text-neutral-300')} />
              <span className="flex-1 text-left">{item.label}</span>
              {item.badge && <span className="w-1.5 h-1.5 rounded-full bg-blue-500" />}
            </>
          );
          return item.to
            ? <Link key={item.key} to={item.to} className={cls}>{inner}</Link>
            : <button key={item.key} className={cls}>{inner}</button>;
        })}
      </div>
    </aside>
  );
}

function ProgramShell({ active, curriculumSub, children, banner, railSingle }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="flex">
        <ProgramSideNav active={active} />
        {curriculumSub && <CurriculumSubNav active={curriculumSub} />}
        <main className="flex-1 min-w-0">
          {banner}
          <div className="px-8 py-8">{children}</div>
        </main>
      </div>
    </div>
  );
}

/* ============ Shared section header for tables ============ */
function ProgSectionHead({ title, count, chips, activeChip, onChip, edit, collapsed, onCollapse }) {
  return (
    <div className="flex items-center gap-3 mb-4">
      <button onClick={onCollapse} className="text-neutral-500"><Icon name={collapsed ? 'chevronDown' : 'chevronUp'} size={16} /></button>
      <h2 className="text-xl font-bold whitespace-nowrap">{title}{count != null && ` (${count})`}</h2>
      {chips && (
        <div className="flex items-center gap-2 ml-2">
          {chips.map(c => (
            <button key={c} onClick={() => onChip && onChip(c)}
              className={`px-3.5 h-7 rounded-full text-[13px] font-medium transition-colors ${activeChip === c ? 'bg-neutral-900 text-white' : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'}`}>
              {c}
            </button>
          ))}
        </div>
      )}
      <div className="flex-1" />
      {edit && <button className="text-neutral-400 hover:text-neutral-700"><Icon name="edit" size={16} /></button>}
    </div>
  );
}

function MiniBar({ pct }) {
  return (
    <div className="flex items-center gap-2.5 min-w-[150px]">
      <div className="flex-1 h-1.5 rounded-full bg-neutral-200 overflow-hidden">
        <div className="h-full rounded-full bg-neutral-900" style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

/* ============ OVERVIEW (admin / learner / preview) ============ */
const OV_MODULES = [
  { n: 1, name: 'Explore AI Basics', due: '12 Jan 2026', rate: 90, count: '36/42', progress: 100, locked: false },
  { n: 2, name: 'Explore Generative AI', due: '12 Jan 2026', rate: 80, count: '32/42', progress: 80, locked: false },
  { n: 3, name: 'Internet Search & Beyond', due: '12 Jan 2026', rate: 40, count: '16/42', progress: 0, locked: false },
  { n: 4, name: 'Explore Responsible AI', due: '12 Jan 2026', rate: 0, count: '0/42', progress: 0, locked: true },
  { n: 5, name: 'Get Started with Microsoft Copilot', due: '12 Jan 2026', rate: 0, count: '0/42', progress: 0, locked: true },
];
const OV_EXPERIENCES = [
  { name: 'Image Gen Crash Course', tag: null, date: '12 Jan 2026  •  14:30', rate: null, status: 'Upcoming', loc: 'Lot 1C, Level G1 (A4 Entran…', locked: true },
  { name: 'Image Gen Crash Course', tag: 'OPTIONAL', date: '12 Jan 2026  •  14:30', rate: null, status: 'Upcoming', loc: 'Lot 1C, Level G1 (A4 Entran…', locked: false },
  { name: 'Image Gen Crash Course', tag: 'COMPLETED', date: '12 Jan 2026  •  14:30', rate: 90, count: '36/42', status: 'Completed', loc: 'Lot 1C, Level G1 (A4 Entran…', done: true },
];
const OV_EXPERTISE = [
  { name: 'Digital Prototyping (Website/App) and Automated Ope…', tag: null, date: '12 Jan 2026  •  14:30', rate: 0, count: '0/42', status: 'Booked' },
  { name: 'Digital Prototyping (Website/App) and A…', tag: 'OPTIONAL', date: '-', rate: 0, count: '0/42', status: 'Pending' },
  { name: 'Digital Prototyping (Website/App) and A…', tag: 'COMPLETED', date: '12 Jan 2026  •  14:30', rate: 40, count: '16/42', status: 'Completed', done: true },
];

/* Upcoming / mandatory item cards (Progress Tracker) — Figma 49099 / 50983 */
const OV_MANDATORY = [
  { tag: 'COURSE', title: 'Explore AI Basics', date: '12 Jun 2026', done: true },
  { tag: 'COURSE', title: 'Submission: AI Fundamentals Quiz', date: '24 Jun 2026', done: true },
  { tag: 'EXPERIENCE', title: 'Workshop: Ethics in AI Development', date: '12 Aug 2026', done: false },
  { tag: 'EXPERTISE', title: 'Expertise: Portfolio Review', date: '12 Aug 2026', done: false },
];
const OV_UPCOMING = [
  { tag: 'COURSE', title: 'Submission: Introduction to Generative AI Assessment', date: '12 Jun 2026', overdue: true },
  { tag: 'COURSE', title: 'Submission: AI Fundamentals Quiz', date: '24 Jun 2026' },
  { tag: 'EXPERIENCE', title: 'Workshop: Ethics in AI Development', date: '12 Aug 2026' },
  { tag: 'EXPERTISE', title: 'Expertise: Portfolio Review', date: '12 Aug 2026' },
];
const UP_TONES = {
  COURSE: 'bg-pink-100 text-pink-600',
  EXPERIENCE: 'bg-amber-100 text-amber-700',
  EXPERTISE: 'bg-blue-100 text-blue-700',
};
const UP_ICONS = { COURSE: 'book', EXPERIENCE: 'calendar', EXPERTISE: 'userStar' };

function UpcomingCard({ tag, title, date, done, overdue, learner }) {
  return (
    <div className="border border-neutral-200 rounded-xl p-3.5 flex flex-col gap-2 bg-white min-h-[132px]">
      <div className="flex items-start justify-between gap-2">
        <span className={`inline-flex items-center gap-1 px-2 h-5 rounded text-[11px] font-bold tracking-wide ${UP_TONES[tag]}`}>
          <Icon name={UP_ICONS[tag]} size={11} /> {tag}
        </span>
        {learner && (done
          ? <span className="w-4 h-4 rounded border-2 border-blue-500 bg-blue-500 text-white flex items-center justify-center flex-shrink-0"><Icon name="check" size={9} strokeWidth={3} /></span>
          : <span className="w-4 h-4 rounded border-2 border-neutral-300 flex-shrink-0" />)}
      </div>
      <p className="text-[13px] font-semibold text-neutral-900 leading-snug flex-1">{title}</p>
      <div className="flex items-center justify-between text-xs pt-1 border-t border-neutral-100">
        <span className={overdue ? 'text-red-500 font-medium' : 'text-neutral-400'}>{overdue ? 'Overdue ' : ''}{date}</span>
        <button className="inline-flex items-center gap-1 text-blue-600 font-medium hover:underline">View details <Icon name="chevronRight" size={12} /></button>
      </div>
    </div>
  );
}

function LearnerStatInline({ tone, label, value }) {
  const tones = { green: 'bg-green-100 text-green-700', amber: 'bg-amber-100 text-amber-700', red: 'bg-red-100 text-red-600' };
  const dots = { green: 'bg-green-500', amber: 'bg-amber-500', red: 'bg-red-500' };
  return (
    <div className="flex items-center gap-2">
      <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-bold tracking-wide ${tones[tone]}`}>
        <span className={`w-1.5 h-1.5 rounded-full ${dots[tone]}`} />{label}
      </span>
      <span className="text-[13px] font-bold text-blue-600">{value}</span>
    </div>
  );
}

function ThumbSquare({ hue = 220, size = 28 }) {
  return <span className="rounded inline-block flex-shrink-0 overflow-hidden" style={{ width: size, height: size, background: `linear-gradient(135deg, oklch(0.6 0.16 ${hue}), oklch(0.42 0.18 ${hue + 30}))` }}><img src={scenePhoto(hue + 7, 72, 72)} alt="" loading="lazy" onError={e => { e.currentTarget.style.display = 'none'; }} className="w-full h-full object-cover" /></span>;
}

function TagPill({ children, tone = 'neutral' }) {
  const tones = { neutral: 'bg-neutral-200 text-neutral-500', done: 'bg-neutral-200 text-neutral-400' };
  return <span className={`inline-flex items-center px-2 h-5 rounded text-[11px] font-bold tracking-wide ${tones[tone]}`}>{children}</span>;
}

const OV_INCOMPLETE = [
  { name: 'Carla Mendoza', email: 'carlamendoza95@gmail.com' },
  { name: 'Oliver Hayes', email: 'oliver.hayes@gmail.com' },
  { name: 'Sophia Carter', email: 'sophia.carter@email.com' },
  { name: 'Ethan Wright', email: 'ethanwright@mail.com' },
  { name: 'Mia Roberts', email: 'mia.roberts@hotmail.com' },
  { name: 'Liam Johnson', email: 'liam.j@example.com' },
];
const OV_COMPLETED = [
  { name: 'Aisha Rahman', email: 'aisha.rahman@gmail.com', date: '10 Jan 2026' },
  { name: 'Daniel Lee', email: 'daniel.lee@gmail.com', date: '09 Jan 2026' },
  { name: 'Nurul Huda', email: 'nurul.huda@gmail.com', date: '08 Jan 2026' },
  { name: 'Marcus Tan', email: 'marcus.tan@mail.com', date: '07 Jan 2026' },
];

/* Figma: Learner completion list (opens from admin "View details" on a module) */
function LearnerCompletionModal({ m, onClose }) {
  const [tab, setTab] = useState('Incomplete');
  const list = tab === 'Incomplete' ? OV_INCOMPLETE : OV_COMPLETED;
  const done = m.count ? m.count : '36/42';
  return (
    <div className="fixed inset-0 z-[70] bg-black/40 flex items-start justify-center p-4 overflow-y-auto" onClick={onClose} style={{ fontFamily: _la }}>
      <div onClick={e => e.stopPropagation()} className="bg-white rounded-2xl w-full max-w-[820px] my-8 p-8" style={{ boxShadow: '0 24px 64px rgba(0,0,0,0.25)' }}>
        <div className="flex items-start justify-between gap-4">
          <h2 className="text-2xl font-bold text-neutral-900" style={{ fontFamily: _pp }}>{m.name}</h2>
          <button onClick={onClose} className="w-9 h-9 rounded-full flex items-center justify-center text-neutral-500 hover:bg-neutral-100"><Icon name="close" size={20} /></button>
        </div>
        <div className="flex items-center justify-between gap-4 mt-3 flex-wrap">
          <div className="flex items-center gap-2.5 text-[13px]">
            <span className="px-2.5 h-6 inline-flex items-center rounded bg-neutral-100 font-bold text-neutral-600 uppercase tracking-wide">Course</span>
            <span className="px-2.5 h-6 inline-flex items-center rounded bg-neutral-100 font-bold text-neutral-600 uppercase tracking-wide">Module {m.n}</span>
            <span className="text-neutral-400 uppercase tracking-wide font-semibold">Due {m.due}</span>
          </div>
          <button className="inline-flex items-center gap-2 h-9 px-4 rounded-full border border-neutral-300 text-sm font-semibold text-neutral-800 hover:bg-neutral-50">Completion Certificate <Icon name="search" size={14} /></button>
        </div>
        <div className="flex items-center gap-3 mt-5">
          <span className="text-lg font-bold text-neutral-900">{m.rate}%</span>
          <div className="flex-1 h-2 rounded-full bg-neutral-200 overflow-hidden"><div className="h-full rounded-full bg-neutral-500" style={{ width: m.rate + '%' }} /></div>
          <span className="text-sm font-bold text-neutral-500">{done}</span>
        </div>
        <div className="flex items-center gap-2.5 mt-7">
          {['Incomplete', 'Completed'].map(t => (
            <button key={t} onClick={() => setTab(t)}
              className={`px-5 h-10 rounded-full text-sm font-semibold transition-colors ${tab === t ? 'bg-neutral-900 text-white' : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'}`}>{t}</button>
          ))}
        </div>
        <div className="flex items-center gap-4 mt-6 mb-2">
          <h3 className="text-xl font-bold text-neutral-900" style={{ fontFamily: _pp }}>{tab} ({list.length})</h3>
          {tab === 'Incomplete' && (
            <button className="inline-flex items-center gap-2 h-9 px-4 rounded-full border border-blue-500 text-blue-600 text-sm font-semibold hover:bg-blue-50"><Icon name="bell" size={15} /> Send Reminder</button>
          )}
        </div>
        <div>
          {list.map((p, i) => (
            <div key={i} className="flex items-center gap-4 py-3.5 border-b border-neutral-100 last:border-0">
              <span className="font-semibold text-neutral-900 w-[190px] flex-shrink-0">{p.name}</span>
              <span className="text-neutral-500 flex-1 truncate">{p.email}</span>
              <span className="text-neutral-400 w-16 text-right">{p.date || '-'}</span>
              <button className="w-8 h-8 rounded-lg flex items-center justify-center text-neutral-500 hover:bg-neutral-100"><Icon name="more" size={16} /></button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ProgramOverviewPage({ initialView = 'admin' }) {
  const [view, setView] = useState(initialView); // 'admin' | 'learner'
  const [expChip, setExpChip] = useState('All');
  const [expertChip, setExpertChip] = useState('All');
  const [modChip, setModChip] = useState('All');
  const [col, setCol] = useState({ mod: false, exp: false, expert: false });
  const isAdmin = view === 'admin';
  const preview = initialView === 'preview';
  const prog = useProg();
  const [cModal, setCModal] = useState(null);

  const banner = preview
    ? <div className="bg-blue-600 text-white text-sm text-center py-3 px-4">You are now previewing this as a learner</div>
    : (!isAdmin
        ? <div className="bg-neutral-900 text-white text-sm flex items-center justify-between px-6 py-3">
            <span>Please complete your Pre-Program Survey before the course begins. It only takes a few minutes!</span>
            <Icon name="arrowRight" size={18} />
          </div>
        : null);

  return (
    <ProgramShell active="overview" banner={banner}>
      <div className="max-w-[min(1960px,90vw)]">
        <div className="flex items-start justify-between gap-4 mb-6">
          <div>
            <h1 className="text-3xl font-bold text-neutral-900">{prog.name}</h1>
            <p className="text-[15px] text-neutral-500 mt-1">Your complete learning journey, milestones, and completion requirements in one place.</p>
          </div>
          {!preview && (
            <button onClick={() => setView(isAdmin ? 'learner' : 'admin')}
              className={`inline-flex items-center gap-2 h-10 px-4 rounded-lg text-sm font-semibold border transition-colors ${isAdmin ? 'bg-white border-neutral-300 text-neutral-900 hover:bg-neutral-50' : 'bg-neutral-900 border-neutral-900 text-white hover:bg-neutral-800'}`}>
              <Icon name="eye" size={16} /> {isAdmin ? 'Learner view' : 'Admin view'}
            </button>
          )}
        </div>

        {/* Progress Tracker */}
        <div className="bg-white border border-neutral-200 rounded-2xl p-7 mb-8">
          <div className="flex items-start justify-between gap-4">
            <h2 className="text-xl font-bold">Progress Tracker</h2>
            <div className="flex items-center gap-2">
              {isAdmin ? (
                <>
                  <span className="text-base font-bold text-blue-600">{prog.completion}%</span>
                  <span className="text-xs font-semibold text-neutral-500 tracking-wide">COMPLETION RATE</span>
                  <span className="px-2 py-0.5 rounded bg-blue-100 text-blue-700 text-[11px] font-bold">ON TRACK</span>
                </>
              ) : (
                <>
                  <span className="text-base font-bold text-blue-600">20%</span>
                  <span className="text-xs font-semibold text-neutral-500 tracking-wide">COMPLETED</span>
                  <span className="px-2 py-0.5 rounded bg-blue-100 text-blue-700 text-[11px] font-bold">ON TRACK</span>
                  <button className="ml-2 inline-flex items-center gap-1.5 text-xs text-neutral-600 border border-neutral-200 rounded-md px-2.5 py-1 hover:bg-neutral-50">
                    Completion certificate <Icon name="shield" size={12} />
                  </button>
                </>
              )}
            </div>
          </div>
          <div className="mt-3 h-1.5 rounded-full bg-neutral-200 overflow-hidden">
            <div className="h-full rounded-full bg-blue-500" style={{ width: isAdmin ? prog.completion + '%' : '20%' }} />
          </div>

          {isAdmin ? (
            <>
              <div className="mt-5 flex items-center gap-x-8 gap-y-2 flex-wrap">
                <LearnerStatInline tone="green" label="ON TRACK" value="35 LEARNERS" />
                <LearnerStatInline tone="amber" label="AT RISK" value="5 LEARNERS" />
                <LearnerStatInline tone="red" label="BEHIND" value="2 LEARNERS" />
              </div>
              <p className="mt-6 text-[15px] font-bold mb-3">Upcoming</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                {OV_UPCOMING.map((c, i) => <UpcomingCard key={i} {...c} />)}
              </div>
            </>
          ) : (
            <>
              <p className="mt-5 text-[15px] font-bold mb-3">2 out of 7 mandatory items finished</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
                {OV_MANDATORY.map((c, i) => <UpcomingCard key={i} learner {...c} />)}
              </div>
              <p className="text-[15px] font-bold mb-3">Upcoming</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                {OV_UPCOMING.map((c, i) => <UpcomingCard key={i} learner {...c} />)}
              </div>
            </>
          )}
        </div>

        {/* Course Modules */}
        <div className="mb-8">
          <ProgSectionHead title="Course Modules" count={6} edit={isAdmin}
            chips={isAdmin ? null : ['All', 'In Progress', 'Completed']} activeChip={modChip} onChip={setModChip}
            collapsed={col.mod} onCollapse={() => setCol(c => ({ ...c, mod: !c.mod }))} />
          {!col.mod && (
            <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[12px] font-bold tracking-wide text-neutral-500 bg-neutral-50 border-b border-neutral-200">
                    <th className="px-5 py-3">COURSE NAME</th>
                    <th className="px-5 py-3">DUE DATE</th>
                    <th className="px-5 py-3">{isAdmin ? 'COMPLETION RATE' : 'PROGRESS'}</th>
                    <th className="px-5 py-3 text-right">ACTIONS</th>
                  </tr>
                </thead>
                <tbody>
                  {OV_MODULES.map((m, i) => (
                    <tr key={i} className="border-b border-neutral-100 last:border-0">
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <span className="text-[11px] font-bold text-neutral-500 bg-neutral-100 rounded px-2 py-1 whitespace-nowrap">MODULE {m.n}</span>
                          <ThumbSquare hue={210 + i * 8} />
                          <span className={`font-bold text-[13px] ${m.locked ? 'text-neutral-400' : 'text-neutral-900'}`}>{m.name}</span>
                          {m.locked && <Icon name="shield" size={13} className="text-neutral-400" />}
                        </div>
                      </td>
                      <td className="px-5 py-4 text-neutral-500 whitespace-nowrap">{m.due}</td>
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-2.5">
                          <span className="text-neutral-700 font-medium w-9">{isAdmin ? `${m.rate}%` : `${m.progress}%`}</span>
                          <MiniBar pct={isAdmin ? m.rate : m.progress} />
                          {isAdmin && <span className="text-blue-600 font-semibold">{m.count}</span>}
                        </div>
                      </td>
                      <td className="px-5 py-4 text-right">
                        {isAdmin ? (
                          <button onClick={() => setCModal(m)} className="inline-flex items-center gap-2 h-9 px-3 border border-neutral-300 rounded-full text-[13px] font-semibold hover:bg-neutral-50">View details <Icon name="search" size={13} /></button>
                        ) : m.locked ? (
                          <button className="inline-flex items-center gap-2 h-9 px-4 border border-neutral-300 rounded-full text-[13px] font-semibold hover:bg-neutral-50">View module <Icon name="search" size={13} /></button>
                        ) : m.progress >= 100 ? (
                          <button className="inline-flex items-center gap-2 h-9 px-4 border border-neutral-300 rounded-full text-[13px] font-semibold text-blue-600">View certificate <Icon name="search" size={13} /></button>
                        ) : m.n === 2 ? (
                          <button className="inline-flex items-center gap-2 h-9 px-4 bg-neutral-900 text-white rounded-full text-[13px] font-semibold">Continue <Icon name="arrowRight" size={13} /></button>
                        ) : (
                          <button className="inline-flex items-center gap-2 h-9 px-4 border border-neutral-300 rounded-full text-[13px] font-semibold hover:bg-neutral-50">View module <Icon name="search" size={13} /></button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Experiences */}
        <div className="mb-8">
          <ProgSectionHead title="Experiences" count={3} edit={isAdmin}
            chips={['All', 'Mandatory', 'Optional', 'Upcoming', 'Completed']} activeChip={expChip} onChip={setExpChip}
            collapsed={col.exp} onCollapse={() => setCol(c => ({ ...c, exp: !c.exp }))} />
          {!col.exp && (
            <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[12px] font-bold tracking-wide text-neutral-500 bg-neutral-50 border-b border-neutral-200">
                    <th className="px-5 py-3">EXPERIENCE NAME</th>
                    <th className="px-5 py-3">DATE &amp; TIME</th>
                    <th className="px-5 py-3">{isAdmin ? 'COMPLETION RATE' : 'LOCATION'}</th>
                    <th className="px-5 py-3 text-right">ACTIONS</th>
                  </tr>
                </thead>
                <tbody>
                  {OV_EXPERIENCES.map((e, i) => (
                    <tr key={i} className={`border-b border-neutral-100 last:border-0 ${e.done ? 'opacity-50' : ''}`}>
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <ThumbSquare hue={20 + i * 30} />
                          <span className="font-bold text-[13px]">{e.name}</span>
                          {e.tag && <TagPill tone={e.done ? 'done' : 'neutral'}>{e.tag}</TagPill>}
                          {e.locked && <Icon name="shield" size={13} className="text-neutral-400" />}
                        </div>
                      </td>
                      <td className="px-5 py-4 text-neutral-500 whitespace-nowrap">{e.date}</td>
                      <td className="px-5 py-4">
                        {isAdmin
                          ? (e.rate != null ? <div className="flex items-center gap-2.5"><MiniBar pct={e.rate} /><span className="text-blue-600 font-semibold">{e.count}</span></div> : <span className="text-neutral-500">{e.status}</span>)
                          : <span className="text-neutral-500">{e.loc}</span>}
                      </td>
                      <td className="px-5 py-4 text-right">
                        {e.done
                          ? <button className="inline-flex items-center gap-2 h-9 px-3 border border-neutral-300 rounded-full text-[13px] font-semibold text-blue-600">View Certificate <Icon name="search" size={13} /></button>
                          : <button className="inline-flex items-center gap-2 h-9 px-3 border border-neutral-300 rounded-full text-[13px] font-semibold hover:bg-neutral-50">View Details <Icon name="search" size={13} /></button>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Expertise */}
        <div className="mb-4">
          <ProgSectionHead title="Expertise" count={3} edit={isAdmin}
            chips={['All', 'Mandatory', 'Optional', 'Completed']} activeChip={expertChip} onChip={setExpertChip}
            collapsed={col.expert} onCollapse={() => setCol(c => ({ ...c, expert: !c.expert }))} />
          {!col.expert && (
            <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[12px] font-bold tracking-wide text-neutral-500 bg-neutral-50 border-b border-neutral-200">
                    <th className="px-5 py-3">EXPERTISE NAME</th>
                    <th className="px-5 py-3">DATE</th>
                    <th className="px-5 py-3">{isAdmin ? 'COMPLETION RATE' : 'STATUS'}</th>
                    <th className="px-5 py-3 text-right">ACTIONS</th>
                  </tr>
                </thead>
                <tbody>
                  {OV_EXPERTISE.map((e, i) => (
                    <tr key={i} className={`border-b border-neutral-100 last:border-0 ${e.done ? 'opacity-50' : ''}`}>
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <ThumbSquare hue={250 + i * 20} />
                          <span className="font-bold text-[13px]">{e.name}</span>
                          {e.tag && <TagPill tone={e.done ? 'done' : 'neutral'}>{e.tag}</TagPill>}
                        </div>
                      </td>
                      <td className="px-5 py-4 text-neutral-500 whitespace-nowrap">{e.date}</td>
                      <td className="px-5 py-4">
                        {isAdmin
                          ? <div className="flex items-center gap-2.5"><MiniBar pct={e.rate} /><span className="text-blue-600 font-semibold">{e.count}</span></div>
                          : <span className="text-neutral-500 uppercase text-xs font-medium tracking-wide">{e.status}</span>}
                      </td>
                      <td className="px-5 py-4 text-right">
                        {e.done
                          ? <button className="inline-flex items-center gap-2 h-9 px-3 border border-neutral-300 rounded-full text-[13px] font-semibold text-blue-600">View Certificate <Icon name="search" size={13} /></button>
                          : (!isAdmin && e.status === 'Pending')
                            ? <button className="inline-flex items-center gap-2 h-9 px-4 bg-neutral-900 text-white rounded-full text-[13px] font-semibold">Book a slot <Icon name="arrowRight" size={13} /></button>
                            : <button className="inline-flex items-center gap-2 h-9 px-3 border border-neutral-300 rounded-full text-[13px] font-semibold hover:bg-neutral-50">View Details <Icon name="search" size={13} /></button>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
      {cModal && <LearnerCompletionModal m={cModal} onClose={() => setCModal(null)} />}
    </ProgramShell>
  );
}

function NextDeadlineRow({ t, d, k }) {
  return (
    <div className="mb-2">
      <p className="text-[13px] font-bold text-blue-600 uppercase tracking-wide">{t}</p>
      <p className="text-xs text-neutral-500">{d}  •  {k}</p>
    </div>
  );
}
function LearnerStat({ tone, label, value }) {
  const tones = { blue: 'bg-blue-100 text-blue-700', amber: 'bg-amber-100 text-amber-700', red: 'bg-red-100 text-red-600' };
  return (
    <div className="flex items-center gap-3">
      <span className={`px-2 py-0.5 rounded text-[11px] font-bold tracking-wide ${tones[tone]}`}>{label}</span>
      <span className="text-[13px] font-bold text-blue-600">{value}</span>
    </div>
  );
}
function MandRow({ done, label }) {
  return (
    <div className="flex items-center gap-2.5">
      {done
        ? <span className="w-5 h-5 rounded-full bg-blue-500 text-white flex items-center justify-center"><Icon name="check" size={12} strokeWidth={3} /></span>
        : <span className="w-5 h-5 rounded-full border-2 border-blue-400" />}
      <span className={`text-[13px] font-bold uppercase tracking-wide ${done ? 'text-neutral-400' : 'text-blue-600'}`}>{label}</span>
    </div>
  );
}

/* ============ PROGRAMME ANALYTICS (admin) — Figma 5289-50429 ============ */
const PA_STATS = [
  { label: 'Active Members', value: '1,509', sub: 'From 3,108 applicants' },
  { label: 'Members', value: '328', sub: '1,358 members' },
  { label: 'Completion Rate', value: '67%', sub: '166 members', tag: 'ON TRACK' },
  { label: 'Confidence Score', value: '9/10', sub: 'From 1,281 members' },
  { label: 'Revenue', value: 'RM 146K', sub: 'This cohort' },
  { label: 'Expert Sessions', value: '2300h', sub: '1,281 members' },
];
const PA_COURSES = [
  ['Gen AI Fundamentals', '12h • 82% complete'], ['Responsible AI Ethics', '12h • 78% complete'],
  ['AI Capstone Project', '12h • 78% complete'], ['Capstone Workshop', '12h • 76% complete'],
  ['Internet Applications', '12h • 68% complete'], ['Python for Data', '12h • 56% complete'],
];
const PA_EXPERIENCES = [
  ['AI in Everyday Life Talk', 'Talks • 14 Apr 2026'], ['Generative AI Workshop', 'Workshop • 22 May 2026'],
  ['Creative Design Thinking', 'Talks • 30 Jun 2026'], ['Health Tech Innovations', 'Webinars • 15 Jul 2026'],
  ['The Rise of Quantum Computing', 'Event • 10 Aug 2026'], ['Design Thinking Sprint', 'Workshop • 25 Sep 2026'],
  ['AI Industry Panel', 'Talks • 05 Oct 2026'], ['Future of Work Summit', 'Event • 18 Nov 2026'],
];
const PA_COACHES = [
  ['Chris Wales', 'AI Strategy • RM 500/ hr'], ['Nadira Tan', 'AI Mentor • RM 350/ hr'], ['Sophia Chen', 'Data Science • RM 400/ hr'],
];
const PA_GEO = [
  ['Kuala Lumpur', 51, '1,663'], ['Selangor', 24, '800'], ['Negeri Sembilan', 10, '306'], ['Penang', 7, '214'], ['Johor Bahru', 5, '152'],
];
const PA_FUNNEL = [
  ['Impressions', '45,200', 100, '–'], ['Views', '12,800', 28, '-72%'], ['Registered', '6,400', 14, '-50%'],
  ['Applied', '4,200', 9.3, '-34%'], ['Accepted', '3,500', 7.7, '-17%'], ['Enrolled', '3,180', 7, '-11%'],
  ['Active', '1,509', 3.3, '-51%'], ['Completed', '412', 1.5, '-73%'],
];
const PA_FB_DIST = [[5, 65], [4, 24], [3, 7], [2, 3], [1, 1]];
const PA_FB_TAGS = [['community', 13], ['engaging', 11], ['insightful', 5], ['skills', 4]];
const PA_FB_QUOTES = [
  ['Finally an AI event that takes ethics seriously. The regulation panel was thought-provoking.', 'Policy Researcher'],
  ['Would have liked more practical frameworks for implementing responsible AI in companies.', 'Policy Researcher'],
];

function PAListColumn({ title, count, items, kind }) {
  return (
    <div>
      <h3 className="font-bold text-lg mb-3">{title} ({count})</h3>
      <div className="space-y-2.5">
        {items.map(([name, meta], i) => (
          <div key={i} className="bg-white border border-neutral-200 rounded-xl p-3.5 flex items-center gap-3">
            <span className="w-9 h-9 rounded-lg flex-shrink-0" style={{ background: `linear-gradient(135deg, oklch(0.7 0.15 ${(i * 47) % 360}), oklch(0.55 0.18 ${(i * 47 + 40) % 360}))` }} />
            <div className="min-w-0">
              <p className="font-bold text-[13px] truncate">{name}</p>
              <p className="text-[12px] text-neutral-500 mt-0.5">{meta}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProgramDashboardPage() {
  const prog = useProg();
  const stats = PA_STATS.map(st => st.label === 'Completion Rate' ? { ...st, value: prog.completion + '%' } : st.label === 'Active Members' ? { ...st, value: String(prog.enrolled) } : st);
  return (
    <ProgramShell active="dashboard">
      <div className="max-w-[min(2000px,92vw)]">
        <div className="flex items-start justify-between gap-4 mb-6">
          <div>
            <h1 className="text-3xl font-bold text-neutral-900">Programme Analytics</h1>
            <p className="text-[15px] text-neutral-500 mt-1">{prog.name} — overview and analytics.</p>
          </div>
          <div className="flex items-center gap-2">
            <div className="flex items-center gap-2 bg-white border border-neutral-200 rounded-lg px-3 h-10 w-56">
              <Icon name="search" size={16} className="text-neutral-400" />
              <input placeholder="Search for..." className="flex-1 text-sm focus:outline-none placeholder:text-neutral-400 bg-transparent" />
            </div>
            <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={15} /> Export</button>
          </div>
        </div>

        <h2 className="text-xl font-bold mb-4">Overview</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-8">
          {stats.map(s => (
            <div key={s.label} className="bg-white border border-neutral-200 rounded-2xl p-5">
              <div className="flex items-center gap-2 mb-3">
                <span className="text-[13px] font-semibold text-neutral-600">{s.label}</span>
                <span className="ml-auto text-neutral-400"><Icon name="arrowUpRight" size={15} /></span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-4xl font-bold tracking-tight">{s.value}</span>
                {s.tag && <span className="px-2 py-0.5 rounded bg-blue-100 text-blue-700 text-[11px] font-bold">{s.tag}</span>}
              </div>
              <div className="text-xs text-neutral-500 mt-2">{s.sub}</div>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-10">
          <PAListColumn title="Courses" count={6} items={PA_COURSES} />
          <PAListColumn title="Experiences" count={8} items={PA_EXPERIENCES} />
          <PAListColumn title="Coaches" count={3} items={PA_COACHES} />
        </div>

        {/* Geographic Distribution */}
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-xl font-bold">Geographic Distribution</h2>
          <button className="text-sm font-semibold text-neutral-600 hover:text-neutral-900">View All</button>
        </div>
        <div className="bg-white border border-neutral-200 rounded-2xl p-6 mb-10">
          <div className="space-y-4">
            {PA_GEO.map(([name, pct, count]) => (
              <div key={name} className="flex items-center gap-4 text-sm">
                <span className="text-base">🇲🇾</span>
                <span className="font-semibold w-36 flex-shrink-0">{name}</span>
                <div className="flex-1 h-2 rounded-full bg-neutral-100 overflow-hidden"><div className="h-full bg-neutral-900 rounded-full" style={{ width: `${pct}%` }} /></div>
                <span className="text-neutral-500 w-10 text-right">{pct}%</span>
                <span className="text-blue-600 font-semibold w-12 text-right">{count}</span>
              </div>
            ))}
          </div>
          <p className="text-xs text-neutral-400 mt-4">+7 more locations</p>
        </div>

        {/* Enrolment Funnel */}
        <h2 className="text-xl font-bold mb-3">Enrolment Funnel</h2>
        <div className="bg-white border border-neutral-200 rounded-2xl p-6 mb-10">
          <div className="space-y-2.5">
            {PA_FUNNEL.map(([label, value, pct, delta]) => (
              <div key={label} className="flex items-center gap-4 text-sm">
                <span className="text-neutral-600 w-24 flex-shrink-0">{label}</span>
                <div className="flex-1 h-6 rounded-md bg-neutral-100 overflow-hidden"><div className="h-full bg-green-500 rounded-md" style={{ width: `${pct}%`, background: 'linear-gradient(90deg, #4ade80, #22c55e)' }} /></div>
                <span className="font-semibold w-14 text-right num-tabular">{value}</span>
                <span className={`w-12 text-right text-xs font-medium ${delta === '–' ? 'text-neutral-400' : 'text-red-500'}`}>{delta}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Feedback */}
        <h2 className="text-xl font-bold mb-3">Feedback</h2>
        <div className="bg-white border border-neutral-200 rounded-2xl p-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <div>
              <div className="flex items-center gap-6">
                <div>
                  <p className="text-sm font-semibold text-neutral-700 mb-1">Average Rating</p>
                  <div className="flex items-center gap-2"><span className="text-4xl font-bold">4.3</span><Stars n={4} size={16} /></div>
                  <p className="text-xs text-neutral-500 mt-2">From 284 attendees</p>
                </div>
                <div className="flex-1 space-y-1.5">
                  {PA_FB_DIST.map(([s, w]) => (
                    <div key={s} className="flex items-center gap-2 text-xs">
                      <span className="text-neutral-500 w-2">{s}</span>
                      <div className="flex-1 h-2 rounded-full bg-neutral-200 overflow-hidden"><div className="h-full bg-amber-400 rounded-full" style={{ width: `${w}%` }} /></div>
                      <span className="text-neutral-400 w-8 text-right">{w}%</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="flex items-center gap-2 mt-5 flex-wrap">
                {PA_FB_TAGS.map(([t, c]) => (
                  <span key={t} className="px-3 h-7 inline-flex items-center rounded-full bg-neutral-100 text-neutral-600 text-[13px]">{t} ({c})</span>
                ))}
              </div>
            </div>
            <div className="space-y-4">
              {PA_FB_QUOTES.map(([q, who], i) => (
                <div key={i}>
                  <p className="text-sm text-neutral-700 italic leading-relaxed">"{q}"</p>
                  <div className="flex items-center gap-2 mt-2 text-xs text-neutral-500"><span className="w-2 h-2 rounded-full bg-amber-400" /> {who}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </ProgramShell>
  );
}

/* ============ PROGRAM FEEDBACK (admin) ============ */
const FB_DIST = [{ s: 5, w: 78 }, { s: 4, w: 64 }, { s: 3, w: 30 }, { s: 2, w: 8 }, { s: 1, w: 5 }];
const FB_REVIEWS = [
  { n: 'Florence Jones', meta: 'Completed program', stars: 4, date: '1 Jan 2026', title: 'Very insightful and practical', body: 'The courses were easy to follow and the speakers during the webinars were very knowledgeable. I would have liked a bit more time for the final assignment, but overall it was a valuable experience.' },
  { n: 'Natalie Andrew', meta: '83% complete', stars: 5, date: '2 Jan 2026', title: 'A great learning community', body: 'One of the best parts of the program was interacting with other participants. The mentors were approachable and gave practical advice that helped me think more clearly about my career path.' },
  { n: 'Marcus Lee', meta: '75% complete', stars: 4, date: '3 Jan 2026', title: 'Engaging content', body: 'The modules were well-structured and kept me engaged throughout. I appreciated the diverse perspectives shared during discussions, though I wish there were more case studies to analyze.' },
  { n: 'Elena Rodriguez', meta: 'Completed program', stars: 5, date: '4 Jan 2026', title: 'Transformative experience', body: 'This program has changed my approach to my work. The skills I gained were immediately applicable, and the networking opportunities were invaluable. I feel much more confident in my abilities.' },
  { n: 'Jordan Smith', meta: '60% complete', stars: 2, date: '5 Jan 2026', title: 'Good start but needs improvement', body: "I found the initial modules helpful, but some areas felt rushed. I hope future sessions will allow more time for in-depth exploration of the topics. I'm looking forward to seeing how it develops." },
];

function Stars({ n, size = 16 }) {
  return (
    <span className="inline-flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map(i => (
        <Icon key={i} name="star" size={size} fill={i <= n ? '#FBBF24' : 'none'} strokeWidth={i <= n ? 0 : 1.5} className={i <= n ? 'text-amber-400' : 'text-neutral-300'} />
      ))}
    </span>
  );
}

function SetToggle({ on, onClick }) {
  return (
    <button onClick={onClick} className={`w-11 h-6 rounded-full transition-colors flex-shrink-0 ${on ? 'bg-neutral-900' : 'bg-neutral-300'}`}>
      <span className={`block w-5 h-5 bg-white rounded-full transition-transform ${on ? 'translate-x-[22px]' : 'translate-x-[2px]'}`} />
    </button>
  );
}
function SetRow({ title, desc, children }) {
  return (
    <div className="flex items-start justify-between gap-6 py-4 border-b border-neutral-100 last:border-0">
      <div className="min-w-0">
        <p className="text-sm font-semibold text-neutral-900">{title}</p>
        {desc && <p className="text-[13px] text-neutral-500 mt-0.5">{desc}</p>}
      </div>
      <div className="flex-shrink-0">{children}</div>
    </div>
  );
}
function SetCard({ title, children }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-6 mb-5">
      <h2 className="text-base font-bold text-neutral-900 mb-2" style={{ fontFamily: _pp }}>{title}</h2>
      {children}
    </div>
  );
}
function SetInput(props) {
  return <input {...props} className={`h-11 px-4 text-sm border border-neutral-300 rounded-lg bg-white focus:outline-none focus:border-neutral-500 ${props.className || ''}`} />;
}

function ProgramSettingsPage() {
  const prog = useProg();
  const [name, setName] = useState(prog.name);
  const [desc, setDesc] = useState('Applied, hands-on programme helping learners build real AI skills for work and entrepreneurship.');
  const [status, setStatus] = useState(prog.status || 'Active');
  const [visibility, setVisibility] = useState('Public');
  const [capacity, setCapacity] = useState('500');
  const [price, setPrice] = useState('RM 49 / month');
  const [approval, setApproval] = useState(true);
  const [enrolOpen, setEnrolOpen] = useState(true);
  const [cert, setCert] = useState(true);
  const [certTitle, setCertTitle] = useState(prog.name + ' — Certificate of Completion');
  const [minPct, setMinPct] = useState('80');
  const [nEnrol, setNEnrol] = useState(true);
  const [nPost, setNPost] = useState(true);
  const [nDigest, setNDigest] = useState(false);
  const [saved, setSaved] = useState(false);
  const save = () => { setProg({ ...prog, name, status }); setSaved(true); setTimeout(() => setSaved(false), 2000); };
  const Seg = ({ options, value, onChange }) => (
    <div className="inline-flex items-center bg-neutral-100 rounded-lg p-1">
      {options.map(o => (
        <button key={o} onClick={() => onChange(o)}
          className={`px-3.5 h-8 rounded-md text-[13px] font-semibold transition-colors ${value === o ? 'bg-white text-neutral-900 shadow-sm' : 'text-neutral-500 hover:text-neutral-800'}`}>{o}</button>
      ))}
    </div>
  );
  return (
    <ProgramShell active="settings">
      <div className="max-w-[820px]">
        <h1 className="text-3xl font-bold text-neutral-900" style={{ fontFamily: _pp }}>Programme Settings</h1>
        <p className="text-[15px] text-neutral-500 mt-1 mb-6">Manage settings for {prog.name}.</p>

        <SetCard title="General">
          <div className="py-4 border-b border-neutral-100">
            <label className="text-sm font-semibold text-neutral-900">Programme name</label>
            <SetInput value={name} onChange={e => setName(e.target.value)} className="w-full mt-2" />
          </div>
          <div className="py-4 border-b border-neutral-100">
            <label className="text-sm font-semibold text-neutral-900">Short description</label>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} rows={3}
              className="w-full mt-2 px-4 py-3 text-sm border border-neutral-300 rounded-lg bg-white focus:outline-none focus:border-neutral-500 resize-none" />
          </div>
          <SetRow title="Status" desc="Controls whether the programme is live and enrollable.">
            <Seg options={['Active', 'Draft', 'Completed']} value={status} onChange={setStatus} />
          </SetRow>
        </SetCard>

        <SetCard title="Enrollment">
          <SetRow title="Visibility" desc="Who can discover and view this programme.">
            <Seg options={['Public', 'Unlisted', 'Private']} value={visibility} onChange={setVisibility} />
          </SetRow>
          <SetRow title="Capacity" desc="Maximum number of enrolled learners.">
            <SetInput type="number" value={capacity} onChange={e => setCapacity(e.target.value)} className="w-28 text-right" />
          </SetRow>
          <SetRow title="Price" desc="Displayed on the programme landing page.">
            <SetInput value={price} onChange={e => setPrice(e.target.value)} className="w-44" />
          </SetRow>
          <SetRow title="Require approval" desc="Manually approve each enrollment request.">
            <SetToggle on={approval} onClick={() => setApproval(v => !v)} />
          </SetRow>
          <SetRow title="Enrollment open" desc="Allow new learners to enroll.">
            <SetToggle on={enrolOpen} onClick={() => setEnrolOpen(v => !v)} />
          </SetRow>
        </SetCard>

        <SetCard title="Certificate">
          <SetRow title="Issue certificate on completion" desc="Automatically award a certificate when a learner finishes.">
            <SetToggle on={cert} onClick={() => setCert(v => !v)} />
          </SetRow>
          {cert && (
            <>
              <div className="py-4 border-b border-neutral-100">
                <label className="text-sm font-semibold text-neutral-900">Certificate title</label>
                <SetInput value={certTitle} onChange={e => setCertTitle(e.target.value)} className="w-full mt-2" />
              </div>
              <SetRow title="Minimum completion" desc="Required completion percentage to qualify.">
                <div className="flex items-center gap-2"><SetInput type="number" value={minPct} onChange={e => setMinPct(e.target.value)} className="w-20 text-right" /><span className="text-sm text-neutral-500">%</span></div>
              </SetRow>
            </>
          )}
        </SetCard>

        <SetCard title="Notifications">
          <SetRow title="New enrollment" desc="Email me when a learner enrolls."><SetToggle on={nEnrol} onClick={() => setNEnrol(v => !v)} /></SetRow>
          <SetRow title="New community post" desc="Email me when a learner posts in the feed."><SetToggle on={nPost} onClick={() => setNPost(v => !v)} /></SetRow>
          <SetRow title="Weekly digest" desc="A weekly summary of programme activity."><SetToggle on={nDigest} onClick={() => setNDigest(v => !v)} /></SetRow>
        </SetCard>

        <div className="bg-white border border-red-200 rounded-2xl p-6 mb-24">
          <h2 className="text-base font-bold text-red-600 mb-2" style={{ fontFamily: _pp }}>Danger zone</h2>
          <SetRow title="Archive programme" desc="Hide the programme and stop new enrollments. You can restore it later.">
            <button className="h-9 px-4 rounded-lg border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Archive</button>
          </SetRow>
          <SetRow title="Delete programme" desc="Permanently remove this programme and all its data.">
            <button className="h-9 px-4 rounded-lg border border-red-300 text-red-600 text-sm font-semibold hover:bg-red-50">Delete</button>
          </SetRow>
        </div>
      </div>

      <div className="sticky bottom-0 -mx-8 px-8 py-4 bg-white/90 backdrop-blur border-t border-neutral-200 flex items-center justify-end gap-3">
        {saved && <span className="text-sm text-green-600 font-medium mr-auto inline-flex items-center gap-1.5"><Icon name="check" size={16} /> Changes saved</span>}
        <button className="h-10 px-5 rounded-lg border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Cancel</button>
        <button onClick={save} className="h-10 px-6 rounded-lg bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">Save changes</button>
      </div>
    </ProgramShell>
  );
}

function ProgramFeedbackPage() {
  const [chip, setChip] = useState(null);
  const prog = useProg();
  return (
    <ProgramShell active="feedback">
      <div className="max-w-[min(1960px,90vw)]">
        <h1 className="text-3xl font-bold text-neutral-900">Program feedback</h1>
        <p className="text-[15px] text-neutral-500 mt-1 mb-6">Learner feedback on {prog.name} — the learning experience and overall journey.</p>

        <div className="bg-white border border-neutral-200 rounded-2xl p-6 max-w-[460px] mb-8">
          <div className="flex items-center gap-8">
            <div>
              <p className="text-sm font-semibold text-neutral-700 mb-1">Average Rating</p>
              <div className="flex items-center gap-2">
                <span className="text-5xl font-bold">{Number(prog.rating).toFixed(1)}</span>
                <Stars n={Math.round(prog.rating)} size={18} />
              </div>
              <p className="text-xs text-neutral-500 mt-2">From 3,108 members</p>
            </div>
            <div className="flex-1 space-y-1.5">
              {FB_DIST.map(d => (
                <div key={d.s} className="flex items-center gap-2">
                  <span className="text-xs text-neutral-500 w-2">{d.s}</span>
                  <div className="flex-1 h-2 rounded-full bg-neutral-200 overflow-hidden"><div className="h-full bg-amber-400 rounded-full" style={{ width: `${d.w}%` }} /></div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="border-t border-neutral-200 pt-6">
          <h2 className="text-xl font-bold mb-4">Reviews (42)</h2>
          <div className="flex items-center gap-2 mb-5">
            {[['community', 13], ['engaging', 11], ['insightful', 5], ['skills', 4]].map(([t, c]) => (
              <button key={t} onClick={() => setChip(chip === t ? null : t)}
                className={`px-3.5 h-8 rounded-full text-[13px] transition-colors ${chip === t ? 'bg-neutral-900 text-white' : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'}`}>
                {t} ({c})
              </button>
            ))}
          </div>
          <div className="space-y-4">
            {FB_REVIEWS.map((r, i) => (
              <div key={i} className="bg-white border border-neutral-200 rounded-2xl p-5 flex gap-4">
                <div className="w-28 flex-shrink-0">
                  <div className="flex items-start gap-2.5">
                    <ThumbSquare hue={20 + i * 40} size={36} />
                    <div className="min-w-0">
                      <p className="font-bold text-[13px] leading-tight">{r.n}</p>
                      <p className="text-[12px] text-neutral-500 mt-0.5">{r.meta}</p>
                    </div>
                  </div>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-3 mb-1.5">
                    <Stars n={r.stars} size={15} />
                    <span className="text-xs text-neutral-500">{r.date}</span>
                  </div>
                  <h3 className="font-bold text-base mb-1">{r.title}</h3>
                  <p className="text-sm text-neutral-600 leading-relaxed">{r.body}</p>
                </div>
              </div>
            ))}
          </div>
          <div className="flex items-center justify-end gap-2 mt-6">
            <button className="w-9 h-9 rounded-full border border-neutral-200 flex items-center justify-center text-neutral-500 hover:bg-neutral-50"><Icon name="chevronLeft" size={15} /></button>
            {[1, 2, 3].map(p => <button key={p} className={`w-9 h-9 rounded-full text-sm font-semibold ${p === 1 ? 'text-neutral-900' : 'text-neutral-400 hover:bg-neutral-50'}`}>{p}</button>)}
            <button className="w-9 h-9 rounded-full border border-neutral-200 flex items-center justify-center text-neutral-500 hover:bg-neutral-50"><Icon name="chevronRight" size={15} /></button>
          </div>
        </div>
      </div>
    </ProgramShell>
  );
}

function ProgramOverviewLearnerPage() { return <ProgramOverviewPage initialView="learner" />; }
function ProgramOverviewPreviewPage() { return <ProgramOverviewPage initialView="preview" />; }

Object.assign(window, {
  ProgramShell, ProgramRail, ProgramSideNav, CurriculumSubNav, ProgSectionHead, MiniBar, ThumbSquare, TagPill, Stars,
  ProgramOverviewPage, ProgramOverviewLearnerPage, ProgramOverviewPreviewPage,
  ProgramDashboardPage, ProgramFeedbackPage, ProgramSettingsPage });
