/* Mereka v2 — Dashboard + Forms suite */

/* =================================================================
   DASHBOARD V2 — matches the "Dashboard-Admin-With program" reference
   ================================================================= */

const DASH_PERSONAL_NAV = [
  { label: 'My Dashboard', to: '/app/dashboard/overview', icon: 'dashboardGrid' },
  { label: 'My Purchases', icon: 'card', children: [
    { label: 'My Programmes', to: '/app/dashboard/programmes', icon: 'programme' },
    { label: 'My Courses', to: '/app/dashboard/courses', icon: 'courses' },
    { label: 'My Experiences', to: '/app/dashboard/bookings', icon: 'calendarStar' },
    { label: 'My Expertise', to: '/app/dashboard/reviews', icon: 'userStar' },
  ] },
  { label: 'My Gigs', to: '/app/dashboard/gigs', icon: 'briefcase' },
];
const DASH_MANAGE_NAV = [
  { label: 'Manage Services', to: '/app/hub/services/experiences', icon: 'settings' },
  { label: 'Manage Gigs', to: '/app/hub/gigs', icon: 'briefcaseGear' },
  { label: 'Manage Programmes', to: '/app/program/manage', icon: 'programmeGear' },
  { label: 'Forms', to: '/app/forms', icon: 'formsBars' },
  { label: 'Broadcast', to: '/app/dashboard/communication-logs', icon: 'broadcast' },
  { label: 'Finance', to: '/app/dashboard/finance', icon: 'dollar' },
  { label: 'Analytics Dashboard', to: '/app/analytics/impact', icon: 'barChart' },
];
const DASH_HUBS = ['Biji-biji Initiative', 'Mereka', 'Studio Kuala'];

/* role: 'personal' (student — no manage section) | 'admin' (hub admin — manage section) */
function useDashRole() {
  const [role, setRole] = useState(() => {
    try { return localStorage.getItem('mereka_dash_role') || 'admin'; } catch (e) { return 'admin'; }
  });
  const update = (r) => {
    setRole(r);
    try { localStorage.setItem('mereka_dash_role', r); } catch (e) {}
  };
  return [role, update];
}

function DashNavItem({ item, active }) {
  const [open, setOpen] = useState(true);
  if (item.children) {
    return (
      <div>
        <button onClick={() => setOpen(o => !o)}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[15px] text-neutral-600 hover:bg-neutral-50 transition-colors">
          <Icon name={item.icon} size={19} className="text-neutral-400 flex-shrink-0" />
          <span className="flex-1 text-left">{item.label}</span>
          <Icon name="chevronDown" size={16} className={`text-neutral-400 transition-transform ${open ? '' : '-rotate-90'}`} />
        </button>
        {open && (
          <div className="mt-0.5 space-y-0.5 pl-5">
            {item.children.map(c => (
              <Link key={c.label} to={c.to}
                className={`flex items-center gap-3 px-3 py-2 rounded-lg text-[15px] transition-colors ${active === c.to ? 'bg-neutral-100 text-neutral-900 font-semibold' : 'text-neutral-600 hover:bg-neutral-50'}`}>
                <Icon name={c.icon} size={18} className={active === c.to ? 'text-neutral-700 flex-shrink-0' : 'text-neutral-400 flex-shrink-0'} />
                <span>{c.label}</span>
              </Link>
            ))}
          </div>
        )}
      </div>
    );
  }
  return (
    <Link to={item.to}
      className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-[15px] transition-colors ${active === item.to ? 'bg-neutral-100 text-neutral-900 font-semibold' : 'text-neutral-600 hover:bg-neutral-50'}`}>
      <Icon name={item.icon} size={19} className={active === item.to ? 'text-neutral-700 flex-shrink-0' : 'text-neutral-400 flex-shrink-0'} />
      <span>{item.label}</span>
    </Link>
  );
}

function DashSideNav({ active }) {
  const [role, setRole] = useDashRole();
  const isAdmin = role === 'admin';
  const selectedHub = useHub();
  const [hubOpen, setHubOpen] = useState(false);
  const hubRef = useRef(null);
  useEffect(() => {
    if (!hubOpen) return;
    const h = (e) => { if (hubRef.current && !hubRef.current.contains(e.target)) setHubOpen(false); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, [hubOpen]);
  const today = new Date();
  const [calYear, setCalYear] = useState(today.getFullYear());
  const [calMonth, setCalMonth] = useState(today.getMonth());
  const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  const dayNames = ['M','T','W','T','F','S','S'];
  const firstDay = new Date(calYear, calMonth, 1).getDay();
  const daysInMonth = new Date(calYear, calMonth + 1, 0).getDate();
  const days = [];
  const startOffset = firstDay === 0 ? 6 : firstDay - 1;
  const prevMonthDays = new Date(calYear, calMonth, 0).getDate();
  for (let i = 0; i < startOffset; i++) {
    days.push({ day: prevMonthDays - startOffset + i + 1, current: false });
  }
  for (let d = 1; d <= daysInMonth; d++) {
    const isToday = d === today.getDate() && calMonth === today.getMonth() && calYear === today.getFullYear();
    days.push({ day: d, current: true, today: isToday });
  }
  let nextDay = 1;
  while (days.length < 35) days.push({ day: nextDay++, current: false });

  const prevMonth = () => {
    if (calMonth === 0) { setCalMonth(11); setCalYear(calYear - 1); }
    else setCalMonth(calMonth - 1);
  };
  const nextMonth = () => {
    if (calMonth === 11) { setCalMonth(0); setCalYear(calYear + 1); }
    else setCalMonth(calMonth + 1);
  };

  return (
    <aside className="hidden lg:block w-[280px] flex-shrink-0 px-5 py-6">
      {/* Account header */}
      <div className="flex items-start justify-between gap-2 mb-4">
        <div className="min-w-0">
          <p className="text-[13px] font-bold tracking-wide uppercase text-neutral-400" style={{ fontFamily: _la }}>{isAdmin ? 'Admin' : 'Personal'}</p>
          <h3 className="text-2xl font-bold text-neutral-900 truncate" style={{ fontFamily: _pp }}>Faiz Fadhillah</h3>
        </div>
        <span className="mt-1 text-[12px] font-bold text-white bg-neutral-700 px-2.5 py-1 rounded-md flex-shrink-0">FREE</span>
      </div>

      <div className="border-t border-neutral-200 my-4" />

      {/* Personal nav (always shown) */}
      <nav className="space-y-0.5 mb-2">
        {DASH_PERSONAL_NAV.map(i => <DashNavItem key={i.label} item={i} active={active} />)}
      </nav>

      {/* Manage section (admin only) */}
      {isAdmin && (
        <>
          <div className="border-t border-neutral-200 my-4" />
          <p className="px-3 mb-1.5 text-[12px] font-bold tracking-wide uppercase text-neutral-400" style={{ fontFamily: _la }}>Switch hub</p>
          <div className="relative mb-1" ref={hubRef}>
            <button onClick={() => setHubOpen(o => !o)} aria-haspopup="listbox" aria-expanded={hubOpen}
              className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg border transition-colors ${hubOpen ? 'border-neutral-300 bg-neutral-50' : 'border-transparent hover:bg-neutral-50'}`}>
              <Avatar name={selectedHub} size={26} />
              <span className="flex-1 text-left text-[15px] font-medium text-neutral-900 truncate" style={{ fontFamily: _la }}>{selectedHub}</span>
              <Icon name="chevronRight" size={16} className={`text-neutral-500 flex-shrink-0 transition-transform ${hubOpen ? 'rotate-90' : ''}`} />
            </button>
            {hubOpen && (
              <div className="absolute left-0 right-0 top-[calc(100%+6px)] z-30 bg-white border border-neutral-200 rounded-xl py-1.5" style={{ boxShadow: '0 12px 32px rgba(0,0,0,0.14)' }} role="listbox">
                <p className="px-3 pt-1 pb-1.5 text-[12px] font-bold uppercase tracking-wide text-neutral-400" style={{ fontFamily: _la }}>Your hubs</p>
                {DASH_HUBS.map(h => (
                  <button key={h} role="option" aria-selected={selectedHub === h}
                    onClick={() => { setHub(h); setHubOpen(false); }}
                    className="w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-neutral-50 transition-colors">
                    <Avatar name={h} size={24} />
                    <span className="flex-1 text-[14px] font-medium text-neutral-900 truncate" style={{ fontFamily: _la }}>{h}</span>
                    {selectedHub === h && <Icon name="check" size={15} strokeWidth={2.5} className="text-blue-600 flex-shrink-0" />}
                  </button>
                ))}
                <div className="border-t border-neutral-100 my-1" />
                <button onClick={() => setHubOpen(false)} className="w-full flex items-center gap-2 px-3 py-2 text-left text-[14px] font-medium text-neutral-600 hover:bg-neutral-50 transition-colors">
                  <Icon name="plus" size={16} className="text-neutral-500" /> Add a hub
                </button>
              </div>
            )}
          </div>
          <nav className="space-y-0.5">
            {DASH_MANAGE_NAV.map(i => <DashNavItem key={i.label} item={i} active={active} />)}
          </nav>
        </>
      )}

      <div className="border-t border-neutral-200 my-4" />

      {/* Calendar */}
      <div>
        <div className="flex items-center justify-between mb-3 px-1">
          <h4 className="text-base font-semibold text-neutral-900" style={{ fontFamily: _pp }}>My Calendar</h4>
          <a href="#" className="text-neutral-700 hover:text-neutral-900"><Icon name="arrowUpRight" size={16} /></a>
        </div>
        <div className="bg-neutral-50 rounded-2xl p-4">
          <div className="flex items-center justify-between mb-3">
            <button onClick={prevMonth} className="text-blue-500 p-1 hover:bg-white rounded"><Icon name="chevronLeft" size={16} /></button>
            <div className="text-base font-bold" style={{ fontFamily: _pp }}><span className="text-neutral-900">{monthNames[calMonth]}</span> <span className="text-blue-500">{calYear}</span></div>
            <button onClick={nextMonth} className="text-blue-500 p-1 hover:bg-white rounded"><Icon name="chevronRight" size={16} /></button>
          </div>
          <div className="grid grid-cols-7 gap-0.5 mb-1">
            {dayNames.map((d, i) => (
              <div key={i} className="text-[12px] font-medium text-neutral-400 text-center py-1">{d}</div>
            ))}
          </div>
          <div className="grid grid-cols-7 gap-0.5">
            {days.map((d, i) => (
              <div key={i} className={`aspect-square flex items-center justify-center text-[13px] rounded-full ${
                !d.current ? 'text-neutral-300' :
                d.today ? 'bg-neutral-900 text-white font-semibold' :
                (i % 7 === 5 || i % 7 === 6) ? 'text-red-500' : 'text-neutral-800'
              }`}>{d.day}</div>
            ))}
          </div>
        </div>
      </div>
    </aside>
  );
}

function SideLink({ item, active }) {
  return (
    <Link to={item.to}
      className={`flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-colors ${active ? 'bg-neutral-100 text-neutral-900 font-semibold' : 'text-neutral-700 hover:bg-neutral-50'}`}>
      <span>{item.label}</span>
      {item.badge && <span className="w-5 h-5 rounded-full bg-blue-500 text-white text-[11px] font-bold flex items-center justify-center">{item.badge}</span>}
    </Link>
  );
}

function DashShell({ children, active }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="flex max-w-[min(2560px,95vw)] mx-auto">
        <DashSideNav active={active} />
        <main className="flex-1 min-w-0 py-6 px-4 lg:px-0 lg:pr-6">
          {children}
        </main>
      </div>
    </div>
  );
}

const DASHBOARD_POSTS = [
  { id: 'p1', author: 'Jessica', tag: 'ADMIN', hub: 'Mereka', date: 'Dec 12 • Posted in Announcements', title: 'Welcome to AI4U!', body: "We're excited to have you here! AI4U is designed to help you upskill in AI—fro…", video: true },
  { id: 'p2', author: 'Dave', tag: 'EXPERT', hub: 'Biji-biji Initiative', date: 'Nov 29 • Posted in Discussions', title: 'The 30 Day Challenge', body: 'I created this challenge to help keep you on track and get quick breakthrough. Check out the #30daychall…' },
  { id: 'p3', author: 'Jessica', tag: 'ADMIN', hub: 'Biji-biji Initiative', date: 'Nov 28 • Posted in Announcements', title: 'Welcome to AI4U!', body: "We're excited to have you here! AI4U is designed to help you upskill in AI—from the basic…" },
];

const DASHBOARD_FEATURED = [
  { id: 'fe1', tag: 'Programme', type: 'Program', hub: 'Mereka', title: 'AI4U', price: '$49 / month', hue: 290 },
  { id: 'fe2', tag: 'Courses', type: 'Course', hub: 'Biji-biji Initiative', title: 'AI Fluency by Microsoft', price: 'FREE', hue: 25 },
  { id: 'fe3', tag: 'Programme', type: 'Program', hub: 'Biji-biji Initiative', title: 'Dynamous AI Mastery', price: '$749 / year', hue: 220 },
  { id: 'fe4', tag: 'Experience', type: 'Experience', hub: 'Mereka', title: 'Bike Sizing and Bike Fitti…', price: 'RM150 / ticket', hue: 340 },
  { id: 'fe5', tag: 'Expertise', type: 'Expertise', hub: 'Mereka', title: 'Brand Identity Sprint', price: 'from RM 8,500', hue: 170 },
];

const DASHBOARD_MILESTONES = [
  { id: 'm1', date: '12 Nov 2025', type: 'Programme Completed', category: 'Learning', title: 'Mereka Career Accelerator', hub: 'Biji-biji Initiative' },
  { id: 'm2', date: '12 Feb 2024', type: 'Career Update', category: 'Career', title: 'Student → Job Seeker' },
  { id: 'm3', date: '12 Feb 2024', type: 'Experience Joined', category: 'Experiences', title: 'Portfolio Sprint: Build Your Fir…', hub: 'Mereka' },
  { id: 'm4', date: '12 Jul 2023', type: 'Programme Completed', category: 'Learning', title: 'AI Fluency by Microsoft', hub: 'Biji-biji Initiative' },
  { id: 'm5', date: '05 May 2026', type: 'Badge Earned', category: 'Achievements', title: 'Curious Mind — 5 bookings', hub: 'Mereka' },
];

const DASHBOARD_ACTIVITIES = [
  { id: 'a1', title: 'AI4U Program', hub: 'Biji-biji Initiative', due: '30 Jun 2026', progress: 65, status: 'In Progress' },
  { id: 'a2', title: 'Mereka Career Accelerator', hub: 'Mereka', due: '15 Aug 2026', progress: 24, status: 'In Progress' },
  { id: 'a3', title: 'Brand Identity Sprint', hub: 'Mereka', due: '02 Sep 2026', progress: 48, status: 'In Progress' },
  { id: 'a4', title: 'AI Fluency by Microsoft', hub: 'Biji-biji Initiative', due: '12 Jul 2023', progress: 100, status: 'Completed' },
];

/* ===== Dashboard Overview ===== */
function UserOverviewPageV2() {
  const [hub, setHub] = useState('All Hubs');
  const [featured, setFeatured] = useState('All');
  const [milestone, setMilestone] = useState('All');
  const [activity, setActivity] = useState('All');

  const matchesHub = (rowHub) => hub === 'All Hubs' || !rowHub || rowHub === hub;
  const filteredPosts = DASHBOARD_POSTS.filter(p => matchesHub(p.hub));
  const filteredFeatured = DASHBOARD_FEATURED.filter(f => (featured === 'All' || f.type === featured) && matchesHub(f.hub));
  const filteredMilestones = DASHBOARD_MILESTONES.filter(m => (milestone === 'All' || m.category === milestone) && matchesHub(m.hub));
  const filteredActivities = DASHBOARD_ACTIVITIES.filter(a => (activity === 'All' || a.status === activity) && matchesHub(a.hub));

  return (
    <DashShell active="/app/dashboard/overview">
      {/* Header */}
      <div className="flex items-start justify-between gap-6 mb-6 flex-wrap">
        <div className="min-w-0">
          <p className="text-sm text-neutral-500 mb-1">Welcome to your dashboard,</p>
          <h1 className="text-4xl font-bold flex items-center gap-3 flex-wrap">
            Faiz Fadhillah
            <Link to="/app/community/member/faiz-fadhillah" className="text-base text-blue-500 font-medium inline-flex items-center gap-1 hover:underline">View Profile <Icon name="arrowUpRight" size={14} /></Link>
          </h1>
          <div className="mt-5 flex items-center gap-2 flex-wrap">
            {['All Hubs', 'Mereka', 'Biji-biji Initiative'].map(h => (
              <button key={h} onClick={() => setHub(h)}
                className={`inline-flex items-center gap-2 h-9 px-4 rounded-full text-sm transition-colors ${hub === h ? 'bg-white border-2 border-neutral-900 font-semibold' : 'bg-white border border-neutral-200 hover:border-neutral-400'}`}>
                {h === 'All Hubs' && hub === 'All Hubs' && <Icon name="check" size={14} strokeWidth={2.5} />}
                {h !== 'All Hubs' && <Avatar name={h} size={20} />}
                {h}
              </button>
            ))}
          </div>
        </div>
        <div className="flex flex-col items-end gap-3 flex-shrink-0">
          <Card padding="p-4" className="!rounded-xl">
            <div className="flex items-center gap-4">
              <Link to="/app/dashboard/finance" className="flex items-center gap-4 group">
                <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #E0CCFF, #D5BAFF)' }}>
                  <Icon name="card" size={20} className="text-neutral-700" />
                </div>
                <div>
                  <p className="text-xs text-neutral-500">Earned with Mereka</p>
                  <p className="text-xl font-bold num-tabular group-hover:text-primary transition-colors">USD 1,000.00</p>
                </div>
              </Link>
              <Link to="/app/dashboard/finance" title="Open Finance" className="text-neutral-500 hover:text-neutral-900"><Icon name="settings" size={16} /></Link>
            </div>
          </Card>
          <Link to="/web/learning-paths"><button className="inline-flex items-center gap-2 h-10 px-4 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">
            Browse Programmes <Icon name="search" size={14} />
          </button></Link>
        </div>
      </div>

      {/* Posts row */}
      {filteredPosts.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 mb-10">
          {filteredPosts.map(p => <PostCard key={p.id} {...p} />)}
        </div>
      ) : (
        <EmptyState message="No posts from this hub yet." className="mb-10" />
      )}

      {/* Featured */}
      <section className="mb-10">
        <div className="flex items-center gap-4 mb-5 flex-wrap">
          <h2 className="text-2xl font-bold">Featured</h2>
          <div className="flex items-center gap-2 flex-wrap">
            {['All', 'Program', 'Course', 'Experience', 'Expertise'].map(t => (
              <button key={t} onClick={() => setFeatured(t)}
                className={`px-4 h-8 rounded-full text-sm transition-colors ${featured === t ? 'bg-neutral-900 text-white font-semibold' : 'bg-neutral-100 text-neutral-700 hover:bg-neutral-200'}`}>
                {t}
              </button>
            ))}
          </div>
        </div>
        {filteredFeatured.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-5">
            {filteredFeatured.map(f => <FeaturedCard key={f.id} {...f} />)}
          </div>
        ) : (
          <EmptyState message="Nothing featured for this filter." />
        )}
      </section>

      {/* My Milestones */}
      <section className="mb-10">
        <div className="flex items-center gap-4 mb-5 flex-wrap">
          <h2 className="text-2xl font-bold">My Milestones</h2>
          <div className="flex items-center gap-2 flex-wrap">
            {['All', 'Learning', 'Career', 'Experiences', 'Achievements'].map(t => (
              <button key={t} onClick={() => setMilestone(t)}
                className={`px-4 h-8 rounded-full text-sm transition-colors ${milestone === t ? 'bg-neutral-900 text-white font-semibold' : 'bg-neutral-100 text-neutral-700 hover:bg-neutral-200'}`}>
                {t}
              </button>
            ))}
          </div>
        </div>
        {filteredMilestones.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
            {filteredMilestones.map(m => <MilestoneCard key={m.id} {...m} />)}
          </div>
        ) : (
          <EmptyState message="No milestones for this filter yet." />
        )}
      </section>

      {/* My Activities */}
      <section className="mb-10">
        <h2 className="text-2xl font-bold mb-5">My Activities</h2>
        <div className="space-y-4">
          <ActivitySection
            title="Programmes"
            filters={['All', 'In Progress', 'Completed']}
            columns={['Programme name', 'Due date', 'Progress', 'Actions']}
            rows={[
              { id: 'pr1', main: { title: 'AI4U Programme', hue: 240, allCaps: true }, status: 'In Progress', due: '12 JAN 2026', progress: 80, action: { label: 'Explore Generative AI', kind: 'primary' } },
              { id: 'pr2', main: { title: 'AI FOR MY FUTURE', hue: 220, allCaps: true }, status: 'Completed', due: '12 JAN 2026', progress: 100, action: { label: 'View Certificate', kind: 'outline', icon: 'search' } },
            ]}
            hub={hub}
            renderRow={renderProgrammeRow}
          />
          <ActivitySection
            title="Experiences"
            filters={['All', 'Coming Up', 'Completed']}
            columns={['Experience name', 'Status', 'Last booked', 'Tickets', 'Actions']}
            rows={[]}
            emptyMessage="You have not signed up for any experience yet."
            emptyCta={{ label: 'Browse experiences', to: '/web/experiences' }}
          />
          <ActivitySection
            title="Jobs"
            filters={['All', 'In Progress', 'Completed']}
            columns={['Job name', 'Status', 'Last booked', 'Profit', 'Actions']}
            rows={[]}
            emptyMessage="You have not applied for any jobs yet."
            emptyCta={{ label: 'Browse jobs', to: '/web/jobs' }}
          />
          <ActivitySection
            title="Expertise"
            filters={['All', 'Coming Up', 'Completed']}
            columns={['Expertise name', 'Status', 'Last booked', 'Tickets', 'Actions']}
            rows={[]}
            emptyMessage="You have not signed up for any expertise yet."
            emptyCta={{ label: 'Browse expertise', to: '/web/expertise' }}
          />
        </div>
      </section>
    </DashShell>
  );
}

function renderProgrammeRow(r) {
  return (
    <>
      <td className="px-5 py-4">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded" style={{ background: `linear-gradient(135deg, oklch(0.62 0.16 ${r.main.hue}), oklch(0.42 0.18 ${r.main.hue + 30}))` }} />
          <span className={`font-bold text-sm ${r.main.allCaps ? 'uppercase tracking-wide' : ''}`}>{r.main.title}</span>
        </div>
      </td>
      <td className="px-5 py-4 text-neutral-700 text-sm">{r.due}</td>
      <td className="px-5 py-4">
        <div className="flex items-center gap-3 max-w-[260px]">
          <span className="text-xs font-semibold num-tabular w-10">{r.progress}%</span>
          <Progress value={r.progress} tone="dark" className="flex-1" />
        </div>
      </td>
      <td className="px-5 py-4">
        {r.action.kind === 'primary' ? (
          <Link to="/app/program/admin/overview/learner"><button className="inline-flex items-center gap-1.5 h-9 px-4 bg-neutral-900 text-white rounded-full text-xs font-semibold hover:bg-neutral-800">
            {r.action.label} <Icon name="arrowRight" size={12} />
          </button></Link>
        ) : (
          <Link to="/app/program/admin/overview/learner"><button className="inline-flex items-center gap-1.5 h-9 px-4 border border-neutral-300 rounded-full text-xs font-semibold hover:bg-neutral-50">
            {r.action.label} {r.action.icon && <Icon name={r.action.icon} size={12} />}
          </button></Link>
        )}
      </td>
    </>
  );
}

function ActivitySection({ title, filters, columns, rows, renderRow, emptyMessage, emptyCta }) {
  const [open, setOpen] = useState(true);
  const [filter, setFilter] = useState(filters[0]);
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
      <div className="flex items-center gap-4 px-5 py-4 border-b border-neutral-100 flex-wrap">
        <button onClick={() => setOpen(!open)} className="flex items-center gap-2 font-bold text-base">
          <Icon name={open ? 'chevronUp' : 'chevronDown'} size={14} className="text-neutral-500" /> {title}
        </button>
        <div className="flex items-center gap-2">
          {filters.map(t => (
            <button key={t} onClick={() => setFilter(t)}
              className={`px-3 h-7 rounded-full text-xs transition-colors ${filter === t ? 'bg-neutral-900 text-white font-semibold' : 'bg-neutral-100 text-neutral-700 hover:bg-neutral-200'}`}>
              {t}
            </button>
          ))}
        </div>
      </div>
      {open && (
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[640px]">
            <thead>
              <tr className="bg-neutral-50 border-b border-neutral-100 text-xs uppercase tracking-wide text-neutral-500">
                {columns.map(c => <th key={c} className="text-left px-5 py-3 font-semibold">{c}</th>)}
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={columns.length} className="px-5 py-10 text-center text-sm text-neutral-600">
                    {emptyMessage}{' '}
                    {emptyCta && <Link to={emptyCta.to} className="underline text-neutral-900 font-medium hover:text-blue-500">{emptyCta.label}</Link>}
                  </td>
                </tr>
              ) : rows.map(r => (
                <tr key={r.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                  {renderRow(r)}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function EmptyState({ message, className = '' }) {
  return (
    <div className={`bg-white border border-dashed border-neutral-200 rounded-2xl py-12 text-center text-sm text-neutral-500 ${className}`}>
      {message}
    </div>
  );
}

function PostCard({ author, tag, hub, date, title, body, video }) {
  const tagColors = tag === 'ADMIN' ? { bg: '#F7B5D3', fg: '#9D174D' } : { bg: '#D9B5F7', fg: '#5B21B6' };
  return (
    <Link to="/app/program/admin/feed" className="block bg-white border border-neutral-200 rounded-2xl p-4 hover:border-neutral-300 transition-colors">
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-2">
          <Avatar name={author} size={36} />
          <div>
            <div className="flex items-center gap-1.5">
              <span className="font-bold text-sm">{author}</span>
              <span className="px-1.5 py-0.5 rounded text-[11px] font-bold" style={{ background: tagColors.bg, color: tagColors.fg }}>{tag}</span>
            </div>
            <div className="text-[12px] text-neutral-500">{date}</div>
          </div>
        </div>
        <div className="flex items-center gap-1.5 text-xs text-neutral-600">
          <Avatar name={hub} size={20} />
          <span>{hub}</span>
        </div>
      </div>
      <div className="flex gap-3">
        <div className="flex-1">
          <h3 className="font-bold text-base mb-1">{title}</h3>
          <p className="text-sm text-neutral-600 line-clamp-2">{body}</p>
        </div>
        {video && (
          <div className="w-20 h-20 rounded-lg bg-neutral-200 flex-shrink-0 relative overflow-hidden ph-grad">
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="w-7 h-7 rounded-full bg-white/90 flex items-center justify-center">
                <Icon name="play" size={12} fill="currentColor" strokeWidth={0} className="text-neutral-900 ml-0.5" />
              </div>
            </div>
          </div>
        )}
      </div>
    </Link>
  );
}

function FeaturedCard({ tag, title, price, hue, type }) {
  const to = { Program: '/web/learning-paths', Course: '/web/courses', Experience: '/web/experiences', Expertise: '/web/expertise' }[type] || '/web';
  return (
    <Link to={to} className="block group bg-white border border-neutral-200 rounded-xl p-4 hover:border-neutral-400 transition-colors">
      <div className="flex items-start gap-3">
        <div className="w-24 h-24 rounded-xl flex-shrink-0" style={{ background: `linear-gradient(135deg, oklch(0.78 0.13 ${hue}), oklch(0.62 0.18 ${hue + 30}))` }} />
        <div className="flex-1 min-w-0 pt-1">
          <span className="text-xs text-neutral-500">{tag}</span>
          <h3 className="font-bold text-base leading-snug line-clamp-2 group-hover:text-blue-600">{title}</h3>
          <p className="text-sm font-medium text-neutral-700 mt-1">{price}</p>
        </div>
      </div>
    </Link>
  );
}

function MilestoneCard({ date, type, title, hub }) {
  return (
    <Link to="/app/community/member/faiz-fadhillah" className="block bg-white border border-neutral-200 rounded-xl p-4 hover:border-neutral-300 transition-colors">
      <div className="flex items-center justify-between mb-3">
        <div className="text-xs text-neutral-500">{date} • {type}</div>
        <button className="text-neutral-400 hover:text-neutral-700"><Icon name="send" size={14} className="rotate-12" /></button>
      </div>
      <h3 className="font-bold text-sm mb-3 line-clamp-1">{title}</h3>
      {hub && (
        <div className="flex items-center gap-1.5 pt-3 border-t border-neutral-100 text-xs text-neutral-500">
          <Avatar name={hub} size={18} />
          <span>{hub}</span>
        </div>
      )}
    </Link>
  );
}

/* =================================================================
   MANAGE FORMS
   ================================================================= */
const FORMS = [
  { id: 'f1', name: 'Pre-program survey', tags: 'Survey', responses: 23, state: 'Active', completion: '75%', updated: 'just now' },
  { id: 'f2', name: 'Your feedback form', tags: 'Feedback', responses: '-', state: 'Scheduled', completion: '-', updated: '3 days ago' },
  { id: 'f3', name: 'My new form', tags: '-', responses: '-', state: 'Closed', completion: '100%', updated: '1 week ago' },
  { id: 'f4', name: 'Program registration form', tags: 'Application', responses: '-', state: 'Draft', completion: '-', updated: '2 weeks ago' },
  { id: 'f5', name: 'My new form', tags: '-', responses: '-', state: 'Draft', completion: '-', updated: '30 Nov 2025' },
];
const FORMS_BY_HUB = [
  FORMS,
  [
    { id: 'mf1', name: 'AI Cohort Application', tags: 'Application', responses: 312, state: 'Active', completion: '64%', updated: '2 hours ago' },
    { id: 'mf2', name: 'NPS — Q2 product pulse', tags: 'Survey', responses: 148, state: 'Active', completion: '88%', updated: '1 day ago' },
    { id: 'mf3', name: 'Beta access request', tags: 'Application', responses: 57, state: 'Scheduled', completion: '-', updated: '3 days ago' },
    { id: 'mf4', name: 'Workshop feedback', tags: 'Feedback', responses: '-', state: 'Draft', completion: '-', updated: '1 week ago' },
  ],
  [
    { id: 'sf1', name: 'Client brief intake', tags: 'Application', responses: 41, state: 'Active', completion: '92%', updated: 'just now' },
    { id: 'sf2', name: 'Project feedback', tags: 'Feedback', responses: 12, state: 'Closed', completion: '100%', updated: '5 days ago' },
    { id: 'sf3', name: 'Discovery questionnaire', tags: 'Survey', responses: '-', state: 'Draft', completion: '-', updated: '2 weeks ago' },
  ],
];

const STATE_TONE = {
  Active: 'text-green-600',
  Scheduled: 'text-amber-500',
  Closed: 'text-neutral-400',
  Draft: 'text-neutral-700',
};
const STATE_DOT = {
  Active: 'bg-green-500',
  Scheduled: 'bg-amber-500',
  Closed: 'bg-neutral-400',
  Draft: 'bg-neutral-700',
};

function ManageFormsPage() {
  const hub = useHub();
  const HUB_FORMS = FORMS_BY_HUB[hubIdx(hub)] || FORMS;
  const [filter, setFilter] = useState('All');
  const [search, setSearch] = useState('');
  const [menuOpen, setMenuOpen] = useState(null);
  const [modal, setModal] = useState(null); // 'share', 'qr', 'delete', 'deleted', 'sent'
  const filtered = HUB_FORMS.filter(f =>
    (filter === 'All' || f.state === filter) &&
    (search === '' || f.name.toLowerCase().includes(search.toLowerCase()))
  );
  return (
    <DashShell active="/app/forms">
      <div className="flex items-start justify-between mb-2 flex-wrap gap-3">
        <div>
          <h1 className="text-3xl font-bold">Manage forms</h1>
          <p className="text-sm text-neutral-500 mt-1">Create and manage your forms.</p>
        </div>
        <div className="flex items-center gap-2">
          <Link to="/app/forms/settings">
            <button className="inline-flex items-center gap-2 h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium bg-white hover:bg-neutral-50">
              <Icon name="settings" size={14} /> Settings
            </button>
          </Link>
          <button className="inline-flex items-center gap-2 h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium bg-white hover:bg-neutral-50">
            <Icon name="upload" size={14} /> Import form
          </button>
          <Link to="/app/forms/builder/new/content">
            <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="plus" size={14} /> Create new form
            </button>
          </Link>
        </div>
      </div>

      <div className="flex items-center gap-3 my-5 flex-wrap">
        <div className="relative w-[280px]">
          <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search in forms..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" />
        </div>
        <div className="flex-1" />
        {['All', 'Active', 'Scheduled', 'Closed', 'Draft'].map(f => (
          <button key={f} onClick={() => setFilter(f)}
            className={`px-4 h-8 rounded-full text-sm transition-colors ${filter === f ? 'bg-neutral-900 text-white font-semibold' : 'bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50'}`}>
            {f}
          </button>
        ))}
      </div>

      <div className="bg-white border border-neutral-200 rounded-2xl overflow-x-auto">
        <table className="w-full text-sm min-w-[900px]">
          <thead>
            <tr className="border-b border-neutral-100 text-neutral-500 text-sm">
              <th className="text-left px-5 py-3 font-medium">Form name</th>
              <th className="text-left px-5 py-3 font-medium">Tags</th>
              <th className="text-left px-5 py-3 font-medium">Responses</th>
              <th className="text-left px-5 py-3 font-medium">State</th>
              <th className="text-left px-5 py-3 font-medium">Completion</th>
              <th className="text-left px-5 py-3 font-medium whitespace-nowrap">
                <span className="inline-flex items-center gap-1">Last Updated <Icon name="chevronDown" size={12} /></span>
              </th>
              <th className="text-left px-5 py-3 font-medium">Action</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr><td colSpan={7} className="px-5 py-12 text-center text-sm text-neutral-500">No forms match this filter.</td></tr>
            ) : filtered.map(f => (
              <tr key={f.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="px-5 py-4">
                  <Link to={`/app/forms/builder/${f.id}/content`} className="font-medium hover:text-blue-600">{f.name}</Link>
                </td>
                <td className="px-5 py-4 text-neutral-600">{f.tags}</td>
                <td className="px-5 py-4 text-neutral-600">{f.responses}</td>
                <td className="px-5 py-4">
                  <span className={`inline-flex items-center gap-2 text-sm ${STATE_TONE[f.state]}`}>
                    <span className={`w-2 h-2 rounded-full ${STATE_DOT[f.state]}`} />
                    {f.state}
                  </span>
                </td>
                <td className="px-5 py-4 text-neutral-600">{f.completion}</td>
                <td className="px-5 py-4 text-neutral-600">{f.updated}</td>
                <td className="px-5 py-4 relative">
                  <button onClick={() => setMenuOpen(menuOpen === f.id ? null : f.id)} className="text-neutral-500 hover:text-neutral-900 p-1">
                    <Icon name="more" size={16} />
                  </button>
                  {menuOpen === f.id && (
                    <FormActionMenu
                      onClose={() => setMenuOpen(null)}
                      onShare={() => { setMenuOpen(null); setModal('share'); }}
                      onDelete={() => { setMenuOpen(null); setModal('delete'); }}
                      formId={f.id}
                    />
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex items-center justify-between mt-4">
        <span className="text-sm text-neutral-500">Showing {filtered.length === 0 ? '0' : '1-' + filtered.length} of {filtered.length}</span>
        <Pagination />
      </div>

      {/* Modals */}
      {modal === 'share' && <ShareFormModal onClose={() => setModal(null)} onSend={() => setModal('sent')} onQR={() => setModal('qr')} />}
      {modal === 'qr' && <QRFormModal onClose={() => setModal(null)} />}
      {modal === 'delete' && <DeleteFormModal onClose={() => setModal(null)} onConfirm={() => setModal('deleted')} />}
      {modal === 'sent' && <SuccessToast title="'My New Form' succesfully sent!" body='"My new form" has been sent to 12 emails.' onClose={() => setModal(null)} />}
      {modal === 'deleted' && <SuccessToast title="Form deleted!" body='"My new form" has been deleted.' onClose={() => setModal(null)} />}
    </DashShell>
  );
}

function Pagination() {
  return (
    <div className="flex items-center gap-1">
      <button className="w-8 h-8 rounded-full border border-neutral-200 flex items-center justify-center hover:bg-neutral-50"><Icon name="chevronLeft" size={14} /></button>
      <button className="w-8 h-8 rounded-full bg-neutral-900 text-white text-sm font-semibold">1</button>
      <button className="w-8 h-8 rounded-full text-sm hover:bg-neutral-100">2</button>
      <button className="w-8 h-8 rounded-full text-sm hover:bg-neutral-100">3</button>
      <button className="w-8 h-8 rounded-full border border-neutral-200 flex items-center justify-center hover:bg-neutral-50"><Icon name="chevronRight" size={14} /></button>
    </div>
  );
}

function FormActionMenu({ onClose, onShare, onDelete, formId }) {
  useEffect(() => {
    const h = () => onClose();
    setTimeout(() => document.addEventListener('click', h, { once: true }), 0);
    return () => document.removeEventListener('click', h);
  }, []);
  const items = [
    { ic: 'edit', label: 'Edit form', to: `/app/forms/builder/${formId}/content` },
    { ic: 'copy', label: 'Duplicate' },
    { ic: 'eye', label: 'View Responses', to: `/app/forms/builder/${formId}/results` },
    { ic: 'trending', label: 'Analytics' },
    { ic: 'send', label: 'Share', onClick: onShare },
    { ic: 'download', label: 'Export Data' },
  ];
  return (
    <div onClick={e => e.stopPropagation()} className="absolute right-8 top-12 w-48 bg-white rounded-xl shadow-lg border border-neutral-100 py-1 z-30">
      {items.map(it => (
        it.to ? (
          <Link key={it.label} to={it.to} className="flex items-center gap-3 px-4 py-2 text-sm hover:bg-neutral-50">
            <Icon name={it.ic} size={14} className="text-neutral-500" /> {it.label}
          </Link>
        ) : (
          <button key={it.label} onClick={it.onClick} className="w-full flex items-center gap-3 px-4 py-2 text-sm hover:bg-neutral-50 text-left">
            <Icon name={it.ic} size={14} className="text-neutral-500" /> {it.label}
          </button>
        )
      ))}
      <div className="border-t border-neutral-100 my-1" />
      <button onClick={onDelete} className="w-full flex items-center gap-3 px-4 py-2 text-sm hover:bg-red-50 text-red-600 text-left">
        <Icon name="trash" size={14} /> Delete
      </button>
    </div>
  );
}

/* =================================================================
   POPUPS
   ================================================================= */
function ModalShell({ children, onClose, maxWidth = 'max-w-md' }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4" onClick={onClose}>
      <div onClick={e => e.stopPropagation()} className={`w-full ${maxWidth} bg-white rounded-2xl shadow-2xl p-6 border border-neutral-100`}>
        {children}
      </div>
    </div>
  );
}

function ShareFormModal({ onClose, onSend, onQR }) {
  const [emails, setEmails] = useState(['young.zheng@uxagents.com', 'nicholashon@uxagents.com', 'florencejones@gmail.com', 'natalie123a@gmail.com']);
  return (
    <ModalShell onClose={onClose} maxWidth="max-w-xl">
      <div className="flex items-start justify-between mb-5">
        <h2 className="text-xl font-bold">Share 'My New Form'</h2>
        <button onClick={onClose} className="text-neutral-500 hover:text-neutral-900"><Icon name="close" size={18} /></button>
      </div>
      <input placeholder="Send to responders' email"
        className="w-full h-12 px-4 text-sm border border-neutral-200 rounded-xl focus:outline-none focus:border-neutral-400 mb-3" />
      <div className="flex flex-wrap gap-2 mb-6">
        {emails.map((e, i) => (
          <span key={i} className="inline-flex items-center gap-2 h-8 px-3 border border-neutral-200 rounded-full text-sm">
            {e}
            <button onClick={() => setEmails(emails.filter((_, j) => j !== i))}><Icon name="close" size={12} className="text-neutral-500" /></button>
          </span>
        ))}
      </div>
      <div className="flex items-center justify-end gap-3">
        <button onClick={onClose} className="h-11 px-6 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Cancel</button>
        <button onClick={onSend} className="h-11 px-6 rounded-full bg-blue-500 text-white text-sm font-semibold hover:bg-blue-600 inline-flex items-center gap-2">
          Send invitation <Icon name="send" size={14} />
        </button>
      </div>
    </ModalShell>
  );
}

function QRFormModal({ onClose }) {
  // 17×17 fake QR
  const grid = Array.from({ length: 17 }, (_, r) =>
    Array.from({ length: 17 }, (_, c) => ((r * 7 + c * 11 + r * c) % 3 === 0))
  );
  return (
    <ModalShell onClose={onClose} maxWidth="max-w-md">
      <div className="flex items-start justify-between mb-1">
        <h2 className="text-xl font-bold">"My New Form" QR code</h2>
        <button onClick={onClose} className="text-neutral-500 hover:text-neutral-900"><Icon name="close" size={18} /></button>
      </div>
      <p className="text-sm text-neutral-500 mb-6">Scan the QR code to open your form.</p>
      <div className="flex justify-center mb-6">
        <div className="p-3 border-2 border-neutral-200 rounded-2xl">
          <div className="grid gap-px" style={{ gridTemplateColumns: 'repeat(17, 8px)', width: 17 * 8 + 16 }}>
            {grid.flatMap((row, r) => row.map((on, c) => {
              const isCorner = (r < 3 && c < 3) || (r < 3 && c >= 14) || (r >= 14 && c < 3);
              return <div key={`${r}-${c}`} style={{ width: 8, height: 8, background: on || isCorner ? '#000' : 'transparent' }} />;
            }))}
          </div>
        </div>
      </div>
      <div className="flex items-center gap-3">
        <button onClick={onClose} className="flex-1 h-11 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Cancel</button>
        <button className="flex-1 h-11 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800 inline-flex items-center justify-center gap-2">
          Download QR code <Icon name="download" size={14} />
        </button>
      </div>
    </ModalShell>
  );
}

function DeleteFormModal({ onClose, onConfirm }) {
  return (
    <ModalShell onClose={onClose} maxWidth="max-w-sm">
      <div className="flex items-start justify-between mb-1">
        <h2 className="text-xl font-bold">Delete "My new form"?</h2>
        <button onClick={onClose} className="text-neutral-500 hover:text-neutral-900"><Icon name="close" size={18} /></button>
      </div>
      <p className="text-sm text-neutral-500 mb-6">This action can't be undone.</p>
      <div className="flex items-center gap-3">
        <button onClick={onClose} className="flex-1 h-11 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Cancel</button>
        <button onClick={onConfirm} className="flex-1 h-11 rounded-full bg-red-600 text-white text-sm font-semibold hover:bg-red-700 inline-flex items-center justify-center gap-2">
          Delete form <Icon name="trash" size={14} />
        </button>
      </div>
    </ModalShell>
  );
}

function SuccessToast({ title, body, onClose }) {
  useEffect(() => {
    const t = setTimeout(onClose, 3000);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="fixed top-24 right-6 z-50 w-[400px] bg-white rounded-xl shadow-lg border border-neutral-200 p-5 animate-[fadeUp_.2s_ease_both]">
      <div className="flex items-start justify-between gap-3 mb-1">
        <h3 className="font-bold text-base">{title}</h3>
        <button onClick={onClose} className="text-neutral-500 hover:text-neutral-900"><Icon name="close" size={16} /></button>
      </div>
      <p className="text-sm text-neutral-500">{body}</p>
    </div>
  );
}

/* =================================================================
   FORM BUILDER — top chrome
   ================================================================= */
function FormBuilderTopBar({ activeTab, formId }) {
  const tabs = [
    { v: 'content', label: 'Content' },
    { v: 'connect', label: 'Connect' },
    { v: 'share', label: 'Share' },
    { v: 'results', label: 'Results' },
  ];
  return (
    <div className="border-b border-neutral-200 bg-white">
      <div className="px-6 h-[68px] flex items-center gap-6">
        <Link to="/app/forms" className="inline-flex items-center gap-3 text-neutral-700 hover:text-neutral-900">
          <Icon name="arrowRight" size={18} className="rotate-180" />
          <span className="font-bold">My New Form</span>
        </Link>
        <div className="flex items-center gap-1 ml-4">
          {tabs.map(t => (
            <Link key={t.v} to={`/app/forms/builder/${formId}/${t.v}`}
              className={`px-4 h-9 inline-flex items-center rounded-full text-sm font-medium transition-colors ${activeTab === t.v ? 'bg-neutral-900 text-white' : 'text-neutral-700 hover:bg-neutral-100'}`}>
              {t.label}
            </Link>
          ))}
        </div>
        <div className="flex-1" />
        {activeTab !== 'results' && (
          <button className="inline-flex items-center gap-2 h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium bg-white hover:bg-neutral-50">
            <span className="w-4 h-4 rounded-full bg-purple-200" /> Design
          </button>
        )}
        <button className="inline-flex items-center gap-2 h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium bg-white hover:bg-neutral-50">
          <Icon name="play" size={12} fill="currentColor" strokeWidth={0} /> Preview
        </button>
        <button className="inline-flex items-center gap-2 h-10 px-5 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">
          <Icon name="send" size={14} /> Publish
        </button>
      </div>
    </div>
  );
}

/* ===== CONTENT TAB ===== */
function FormBuilderContentPage({ formId = 'new' }) {
  const [pages, setPages] = useState([
    { id: 'welcome', label: 'Welcome screen', kind: 'welcome' },
    { id: 'basic', label: 'Basic info', kind: 'questions' },
  ]);
  const [activePage, setActivePage] = useState('basic');
  const cur = pages.find(p => p.id === activePage);
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <FormBuilderTopBar activeTab="content" formId={formId} />
      <div className="grid grid-cols-1 lg:grid-cols-[220px_1fr_280px] gap-6 px-6 py-6">
        <PagesPanel pages={pages} setPages={setPages} active={activePage} onSelect={setActivePage} />
        <div>
          {cur?.kind === 'welcome' ? <WelcomeCanvas /> : <QuestionsCanvas />}
        </div>
        <div>
          {cur?.kind === 'welcome' ? <WelcomePanel /> : <QuestionPanel />}
        </div>
      </div>
    </div>
  );
}

function PagesPanel({ pages, setPages, active, onSelect }) {
  const [menuId, setMenuId] = useState(null);
  return (
    <aside className="bg-white border border-neutral-200 rounded-2xl p-4 h-fit">
      <h3 className="font-bold mb-3">Pages</h3>
      <div className="space-y-2">
        {pages.map(p => (
          <div key={p.id} className="relative">
            <div onClick={() => onSelect(p.id)} role="button" tabIndex={0}
              className={`w-full flex items-center justify-between px-3 h-10 rounded-lg border text-sm cursor-pointer transition-colors ${active === p.id ? 'bg-neutral-100 border-neutral-300 font-medium' : 'bg-white border-neutral-200 hover:bg-neutral-50'}`}>
              <span className="truncate">{p.label}</span>
              <button onClick={e => { e.stopPropagation(); setMenuId(menuId === p.id ? null : p.id); }} className="text-neutral-500 hover:text-neutral-900 p-1"><Icon name="more" size={14} /></button>
            </div>
            {menuId === p.id && <PageActionMenu onClose={() => setMenuId(null)} />}
          </div>
        ))}
        <button onClick={() => setPages([...pages, { id: 'p' + Date.now(), label: 'New page', kind: 'questions' }])}
          className="w-full flex items-center justify-between px-3 h-10 rounded-lg border border-dashed border-neutral-300 text-sm text-neutral-600 hover:bg-neutral-50">
          Add page <span className="w-5 h-5 rounded-full border border-neutral-300 flex items-center justify-center"><Icon name="plus" size={10} /></span>
        </button>
      </div>
    </aside>
  );
}

function PageActionMenu({ onClose }) {
  useEffect(() => {
    setTimeout(() => document.addEventListener('click', onClose, { once: true }), 0);
    return () => document.removeEventListener('click', onClose);
  }, []);
  return (
    <div onClick={e => e.stopPropagation()} className="absolute right-0 top-11 w-40 bg-white rounded-xl shadow-lg border border-neutral-100 py-1 z-20">
      <button className="w-full flex items-center gap-3 px-4 py-2 text-sm hover:bg-neutral-50 text-left">
        <Icon name="copy" size={14} className="text-neutral-500" /> Duplicate
      </button>
      <button className="w-full flex items-center gap-3 px-4 py-2 text-sm hover:bg-red-50 text-red-600 text-left">
        <Icon name="trash" size={14} /> Delete
      </button>
    </div>
  );
}

function WelcomeCanvas() {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[600px] relative">
      <div className="absolute top-5 right-5 w-7 h-7"><MerekaLogo /></div>
      <div className="flex flex-col items-center justify-center min-h-[520px]">
        <div className="w-[300px] h-[300px] bg-neutral-200 rounded-lg mb-6" />
        <h2 className="text-2xl font-bold mb-2">Hi! Welcome to...</h2>
        <p className="text-neutral-500 text-center mb-6">Description (Optional)</p>
        <button className="h-12 px-10 bg-neutral-900 text-white rounded-full font-semibold">Start</button>
      </div>
    </div>
  );
}

function WelcomePanel() {
  return (
    <aside className="bg-white border border-neutral-200 rounded-2xl p-4 h-fit">
      <h3 className="font-bold mb-4">Welcome screen</h3>
      <div className="border border-neutral-200 rounded-lg p-4 mb-4">
        <p className="text-xs text-neutral-500 mb-2">Button</p>
        <div className="relative">
          <input defaultValue="Start" className="w-full h-10 px-3 pr-10 text-sm border border-neutral-200 rounded-lg focus:outline-none focus:border-neutral-400" />
          <button className="absolute right-3 top-1/2 -translate-y-1/2 text-neutral-500"><Icon name="edit" size={14} /></button>
        </div>
        <p className="text-[11px] text-neutral-400 mt-1 text-right">5/25 max</p>
      </div>
      <button className="w-full h-10 border border-neutral-200 rounded-lg text-sm inline-flex items-center justify-center gap-2 hover:bg-neutral-50">
        <Icon name="upload" size={14} className="text-neutral-500" /> image or video
      </button>
    </aside>
  );
}

function QuestionsCanvas() {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[600px] relative">
      <div className="absolute top-5 right-5 w-7 h-7"><MerekaLogo /></div>
      <p className="text-xs font-bold text-neutral-700 uppercase tracking-wide">BASIC INFO</p>
      <p className="text-sm text-neutral-600 mb-8">Tell us about yourself!</p>

      <div className="space-y-8">
        <div className="flex items-start gap-3">
          <Icon name="menu" size={14} className="text-neutral-400 mt-2" />
          <span className="text-neutral-500 text-sm mt-1.5">1</span>
          <div className="flex-1">
            <h3 className="text-lg font-medium">Tell us your name</h3>
            <p className="text-sm text-neutral-500 mb-3">Description (Optional)</p>
            <input placeholder="Short answer text" className="w-full h-12 px-4 text-sm border border-neutral-200 rounded-lg" />
          </div>
        </div>

        <div className="flex items-start gap-3">
          <Icon name="menu" size={14} className="text-neutral-400 mt-2" />
          <span className="text-neutral-500 text-sm mt-1.5">2</span>
          <div className="flex-1">
            <h3 className="text-lg text-neutral-400">Ask a question...</h3>
            <p className="text-sm text-neutral-500 mb-3">Description (Optional)</p>
            <div className="space-y-2">
              <div className="flex items-center gap-2.5">
                <span className="w-5 h-5 rounded-full border-2 border-neutral-300" />
                <span className="text-sm text-neutral-700">Option 1</span>
              </div>
              <div className="flex items-center gap-2.5">
                <span className="w-5 h-5 rounded-full border-2 border-neutral-300" />
                <span className="text-sm text-neutral-500"><a href="#" className="underline">Add option</a> or <a href="#" className="text-blue-500 underline">Add "Other"</a></span>
              </div>
            </div>
          </div>
        </div>

        <button className="ml-12 inline-flex items-center gap-2 text-sm text-neutral-500 hover:text-neutral-900">
          <Icon name="plus" size={14} /> Add question
        </button>
      </div>
    </div>
  );
}

function QuestionPanel() {
  const [questions] = useState([
    { id: 1, type: 'Short text', required: false, hasImage: true },
    { id: 2, type: 'Multiple choice', required: false },
  ]);
  return (
    <aside className="bg-white border border-neutral-200 rounded-2xl p-4 h-fit">
      <h3 className="font-bold mb-3">Question</h3>
      <div className="space-y-2 mb-5">
        <RadioRow2 label="text" checked />
        <RadioRow2 label="image/video" />
      </div>

      {questions.map(q => (
        <div key={q.id} className="border border-neutral-200 rounded-lg p-3 mb-3">
          <div className="flex items-center justify-between mb-3">
            <span className="text-sm font-medium">Question {q.id}</span>
            <div className="flex items-center gap-1.5 text-neutral-400">
              <button><Icon name="trash" size={14} /></button>
              <button><Icon name="upload" size={14} /></button>
              <button><Icon name="more" size={14} /></button>
            </div>
          </div>
          <div className="relative mb-3">
            <select className="w-full h-9 px-3 pr-8 text-sm border border-neutral-200 rounded-lg appearance-none focus:outline-none">
              <option>{q.type}</option>
            </select>
            <Icon name="chevronDown" size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none" />
          </div>
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs text-neutral-500">Required</span>
            <Toggle2 on={q.required} />
          </div>
          {q.hasImage && (
            <div className="mt-3 flex items-center justify-between h-9 px-3 border border-neutral-200 rounded-lg text-sm">
              <span className="text-neutral-700">example.png</span>
              <button className="text-neutral-500"><Icon name="close" size={12} /></button>
            </div>
          )}
        </div>
      ))}

      <button className="w-full h-10 border border-neutral-200 rounded-lg text-sm inline-flex items-center justify-center gap-2 hover:bg-neutral-50 text-neutral-700">
        <Icon name="plus" size={14} /> Add question
      </button>
    </aside>
  );
}

function RadioRow2({ label, checked }) {
  return (
    <label className="flex items-center gap-2 cursor-pointer">
      <span className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${checked ? 'border-neutral-900' : 'border-neutral-400'}`}>
        {checked && <span className="w-2 h-2 rounded-full bg-neutral-900" />}
      </span>
      <span className="text-sm">{label}</span>
    </label>
  );
}

function Toggle2({ on }) {
  return (
    <span className={`relative inline-block w-9 h-5 rounded-full ${on ? 'bg-neutral-900' : 'bg-neutral-300'}`}>
      <span className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${on ? 'translate-x-4' : ''}`} />
    </span>
  );
}

/* ===== CONNECT TAB ===== */
function FormBuilderConnectPage({ formId = 'new' }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <FormBuilderTopBar activeTab="connect" formId={formId} />
      <div className="px-6 py-8 max-w-[min(1480px,88vw)]">
        <h2 className="text-2xl font-bold mb-1">Integrations</h2>
        <p className="text-sm text-neutral-500 mb-6">Save time and effort with these integrations for Typeform</p>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <IntegrationCard color="#EBE0FF" title="ClickUp Integration" desc="Automatically send form responses to ClickUp" />
          <IntegrationCard color="#D6F3DC" title="Google Sheets Integration" desc="Send your responses directly to Google Sheets" />
        </div>
      </div>
    </div>
  );
}

function IntegrationCard({ color, title, desc }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-xl p-5">
      <div className="w-10 h-10 rounded-lg mb-12" style={{ background: color }} />
      <h3 className="font-bold mb-1">{title}</h3>
      <p className="text-sm text-neutral-500">{desc}</p>
    </div>
  );
}

/* ===== SHARE TAB ===== */
function FormBuilderSharePage({ formId = 'new' }) {
  const [privacy, setPrivacy] = useState('private');
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <FormBuilderTopBar activeTab="share" formId={formId} />
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-6 px-6 py-6">
        <div className="space-y-4">
          <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[560px] relative flex flex-col items-center justify-center">
            <div className="absolute top-5 right-5 w-7 h-7"><MerekaLogo /></div>
            <h2 className="text-2xl font-bold mb-2">Hi! Welcome to...</h2>
            <p className="text-neutral-500 text-center mb-6">Description (Optional)</p>
            <button className="h-12 px-10 bg-neutral-900 text-white rounded-full font-semibold">Start</button>
          </div>
          <div className="flex items-center gap-2">
            <input readOnly value="https://ewg90vwe42i.mereka.my/to/khVpKRf6"
              className="flex-1 h-11 px-4 text-sm border border-neutral-200 rounded-lg bg-white" />
            <CopyButton text="https://ewg90vwe42i.mereka.my/to/khVpKRf6" label="Copy link" icon={null} className="h-11 px-5 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800" />
          </div>
        </div>

        <div className="space-y-4">
          <div className="bg-white border border-neutral-200 rounded-2xl p-5">
            <h3 className="font-bold mb-4">Share options</h3>
            <p className="text-sm text-neutral-700 mb-2">Form Privacy</p>
            <div className="space-y-2 mb-4">
              <button onClick={() => setPrivacy('public')} className="w-full text-left">
                <RadioRow2Text label="Everyone can respond to this form." checked={privacy === 'public'} />
              </button>
              <button onClick={() => setPrivacy('private')} className="w-full text-left">
                <RadioRow2Text label="Set form as private." checked={privacy === 'private'} />
              </button>
            </div>
            {privacy === 'private' && (
              <>
                <input placeholder="Password to access form"
                  className="w-full h-11 px-4 text-sm border border-neutral-200 rounded-lg mb-3 focus:outline-none focus:border-neutral-400" />
                <button className="w-full h-11 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800 mb-5">Save password</button>
              </>
            )}

            <p className="text-sm text-neutral-700 mb-2">Share on Social Media</p>
            <div className="space-y-2 mb-5">
              <SocialBtn label="Facebook" color="#1877F2" />
              <SocialBtn label="Linkedin" color="#0A66C2" />
              <SocialBtn label="X" color="#000" />
            </div>

            <p className="text-sm text-neutral-700 mb-2">Share via QR code</p>
            <button className="w-full h-11 px-4 border border-neutral-200 rounded-lg text-sm inline-flex items-center gap-2 mb-5 hover:bg-neutral-50">
              <span className="grid grid-cols-1 sm:grid-cols-2 gap-0.5 w-4 h-4">
                <span className="bg-neutral-900 rounded-sm" /><span className="bg-neutral-900 rounded-sm" />
                <span className="bg-neutral-900 rounded-sm" /><span className="bg-neutral-900 rounded-sm" />
              </span>
              QR code
            </button>

            <p className="text-sm text-neutral-700 mb-2">Send to responder's email</p>
            <button className="w-full h-11 px-4 border border-neutral-200 rounded-lg text-sm inline-flex items-center gap-2 hover:bg-neutral-50">
              <Icon name="send" size={14} /> Email
            </button>
          </div>

          <div className="bg-white border border-neutral-200 rounded-2xl p-5">
            <h3 className="font-bold mb-3">Form details</h3>
            <p className="text-sm font-medium mb-1">Social preview</p>
            <p className="text-xs text-neutral-500 mb-3">Preview that appears when you share a link (Facebook, Twitter/X, LinkedIn).</p>
            <div className="aspect-[1.9/1] bg-neutral-200 rounded-lg mb-2" />
            <button className="w-full h-10 px-3 border border-neutral-200 rounded-lg text-sm inline-flex items-center justify-between hover:bg-neutral-50 mb-2">
              Upload <Icon name="upload" size={14} className="text-neutral-500" />
            </button>
            <p className="text-xs text-neutral-500 mb-4">1200 × 630 pixels. 5mb max.</p>
            <label className="text-sm font-medium mb-1.5 block">Form title</label>
            <input defaultValue="My New Form" className="w-full h-10 px-3 text-sm border border-neutral-200 rounded-lg mb-3" />
            <label className="text-sm font-medium mb-1.5 block">Form description</label>
            <textarea rows={3} placeholder="Form description" className="w-full px-3 py-2 text-sm border border-neutral-200 rounded-lg resize-none mb-4" />
            <button className="w-full h-11 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">Save changes</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function RadioRow2Text({ label, checked }) {
  return (
    <span className="flex items-start gap-2 py-1">
      <span className={`mt-0.5 w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${checked ? 'border-neutral-900' : 'border-neutral-400'}`}>
        {checked && <span className="w-2 h-2 rounded-full bg-neutral-900" />}
      </span>
      <span className="text-sm text-neutral-700">{label}</span>
    </span>
  );
}

function SocialBtn({ label, color }) {
  return (
    <button className="w-full h-10 px-3 border border-neutral-200 rounded-lg text-sm inline-flex items-center gap-2 hover:bg-neutral-50">
      <span className="w-5 h-5 rounded-full flex items-center justify-center text-white text-[11px] font-bold" style={{ background: color }}>{label[0]}</span>
      {label}
    </button>
  );
}

/* ===== RESULTS TAB ===== */
function FormBuilderResultsPage({ formId = 'new' }) {
  const [view, setView] = useState('respondents');
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <FormBuilderTopBar activeTab="results" formId={formId} />
      <div className="grid grid-cols-1 lg:grid-cols-[200px_1fr] gap-6 px-6 py-6">
        <aside className="space-y-3">
          <div className="bg-white border border-neutral-200 rounded-2xl p-3">
            <h3 className="font-bold mb-2 px-2">Results</h3>
            <div className="space-y-1">
              <button onClick={() => setView('respondents')}
                className={`w-full flex items-center gap-2 px-3 h-9 rounded-lg text-sm ${view === 'respondents' ? 'bg-neutral-100 font-medium' : 'hover:bg-neutral-50'}`}>
                <Icon name="user" size={14} /> Respondents
              </button>
              <button onClick={() => setView('responses')}
                className={`w-full flex items-center gap-2 px-3 h-9 rounded-lg text-sm ${view === 'responses' ? 'bg-neutral-100 font-medium' : 'hover:bg-neutral-50'}`}>
                <Icon name="layers" size={14} /> Responses
              </button>
            </div>
          </div>
          <div className="bg-white border border-neutral-200 rounded-2xl p-3">
            <h3 className="font-bold mb-2 px-2">Actions</h3>
            <div className="space-y-1">
              <button className="w-full flex items-center gap-2 px-3 h-9 rounded-lg text-sm hover:bg-neutral-50 border border-neutral-200">
                <Icon name="plus" size={14} /> Add certificate
              </button>
              <button className="w-full flex items-center gap-2 px-3 h-9 rounded-lg text-sm hover:bg-neutral-50 border border-neutral-200">
                <Icon name="download" size={14} /> Export data
              </button>
            </div>
          </div>
        </aside>

        <div>
          {view === 'respondents' ? <RespondentsView /> : <ResponsesView />}
        </div>
      </div>
    </div>
  );
}

function RespondentsView() {
  const [detail, setDetail] = useState(null);
  const respondents = [
    'florencejones@gmail.com', 'natalie123a@gmail.com', 'jamey_james@gmail.com',
    'carlamendoza95@gmail.com', 'oliver.hayes@gmail.com', 'sophia.carter@email.com',
    'ethanwright@mail.com', 'mia.roberts@hotmail.com', 'liam.j@example.com', 'liam.j@example.com',
  ];
  return (
    <>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCardF label="Total view/ link open" value="154" sub="sent to 223 members" />
        <StatCardF label="Total Responses" value="128" sub="sent to 223 members" />
        <StatCardF label="Avg Time" value="2m 43s" />
        <StatCardF label="Latest Response" value="Mar 6" />
      </div>
      <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4">
          <h3 className="text-lg font-bold">Respondents (128)</h3>
        </div>
        <div className="flex items-center justify-between px-5 pb-3">
          <div className="relative w-[280px]">
            <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
            <input placeholder="Search responses..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full" />
          </div>
          <div className="flex items-center gap-2">
            <button className="text-neutral-500"><Icon name="filter" size={16} /></button>
            <button className="text-neutral-500"><Icon name="download" size={16} /></button>
          </div>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="border-y border-neutral-100 text-neutral-500">
              <th className="px-5 py-3 text-left font-medium w-10"><input type="checkbox" /></th>
              <th className="px-5 py-3 text-left font-medium">Email</th>
              <th className="px-5 py-3 text-right font-medium">Date Submitted</th>
              <th className="px-5 py-3 text-right font-medium">Action</th>
            </tr>
          </thead>
          <tbody>
            {respondents.map((e, i) => (
              <tr key={i} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="px-5 py-3"><input type="checkbox" /></td>
                <td className="px-5 py-3 text-neutral-700">{e}</td>
                <td className="px-5 py-3 text-right text-neutral-600">3/10/2024, 12:00:00 AM</td>
                <td className="px-5 py-3 text-right">
                  <div className="inline-flex items-center gap-2">
                    <button onClick={() => setDetail(e)} className="h-8 px-4 border border-blue-500 text-blue-500 rounded-full text-xs font-semibold hover:bg-blue-50">View Response</button>
                    <button className="text-neutral-500"><Icon name="more" size={14} /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="flex items-center justify-between px-5 py-4">
          <span className="text-sm text-neutral-500">Showing 1-10 of 128</span>
          <Pagination />
        </div>
      </div>
      {detail && <ResponseDetailDrawer email={detail} onClose={() => setDetail(null)} />}
    </>
  );
}

function StatCardF({ label, value, sub }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl p-5 relative">
      <button className="absolute top-3 right-3 text-neutral-400"><Icon name="arrowUpRight" size={14} /></button>
      <p className="text-xs text-neutral-500 mb-1">{label}</p>
      <p className="text-3xl font-bold">{value}</p>
      {sub && <p className="text-xs text-neutral-500 mt-1">{sub}</p>}
    </div>
  );
}

const RESPONSE_ANSWERS = [
  { type: 'Short text', answer: 'Lorem ipsum' },
  { type: 'Long text', answer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,' },
  { type: 'Multiple choice', options: ['Option 1', 'Option 2', 'Option 3', 'Option 4'] },
  { type: 'File upload', file: 'example.png' },
  { type: 'Rating', rating: 3 },
  { type: 'Long text', answer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,' },
  { type: 'Long text', answer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,' },
  { type: 'Short text', answer: 'Lorem ipsum' },
];

function ResponseDetailDrawer({ email, onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);
  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div onClick={e => e.stopPropagation()}
        className="w-full max-w-[440px] h-full bg-white shadow-2xl overflow-y-auto animate-[slideInRight_.22s_ease_both]">
        <div className="sticky top-0 bg-white border-b border-neutral-100 px-6 pt-5 pb-4 z-10">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3 min-w-0">
              <div className="flex flex-col -space-y-1 text-neutral-700">
                <button className="hover:text-neutral-900"><Icon name="chevronDown" size={16} /></button>
                <button className="hover:text-neutral-900"><Icon name="chevronDown" size={16} className="rotate-180" /></button>
              </div>
              <span className="font-bold text-lg truncate">{typeof email === 'string' ? email : 'name@example.com'}</span>
            </div>
            <button onClick={onClose} className="text-neutral-500 hover:text-neutral-900 flex-shrink-0"><Icon name="close" size={20} /></button>
          </div>
          <p className="text-sm text-neutral-500 mt-2">Submitted 1 Apr 2026 20:08</p>
        </div>

        <div className="p-5 space-y-3">
          {RESPONSE_ANSWERS.map((q, i) => (
            <div key={i} className="border border-neutral-200 rounded-xl p-4">
              <h3 className="font-bold text-base">Question {i + 1}</h3>
              <p className="text-sm font-semibold text-neutral-500 mt-0.5">{q.type}</p>
              <div className="mt-3">
                {q.answer && <p className="text-[15px] text-neutral-500 leading-relaxed">{q.answer}</p>}
                {q.options && (
                  <div className="flex flex-wrap gap-2">
                    {q.options.map(o => <span key={o} className="inline-flex items-center px-3 h-9 border border-neutral-200 rounded-lg text-sm text-neutral-600">{o}</span>)}
                  </div>
                )}
                {q.file && <a href="#" className="text-[15px] text-neutral-500 underline">{q.file}</a>}
                {q.rating != null && (
                  <div className="flex items-center gap-1.5 text-amber-400">
                    {Array.from({ length: q.rating }, (_, k) => <Icon key={k} name="star" size={24} fill="currentColor" strokeWidth={0} />)}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ResponsesView() {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
      <div className="px-5 py-4">
        <h3 className="text-lg font-bold">Responses (128)</h3>
      </div>
      <div className="flex items-center justify-between px-5 pb-3">
        <div className="relative w-[280px]">
          <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
          <input placeholder="Search responses..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full" />
        </div>
        <div className="flex items-center gap-2">
          <button className="text-neutral-500"><Icon name="filter" size={16} /></button>
          <button className="text-neutral-500"><Icon name="download" size={16} /></button>
        </div>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-sm min-w-[1200px]">
          <thead>
            <tr className="border-y border-neutral-100 text-neutral-700 bg-white">
              <th className="px-4 py-3 text-left font-medium w-10"><input type="checkbox" /></th>
              <th className="px-4 py-3 text-left font-medium">Email</th>
              <th className="px-4 py-3 text-left font-medium">Response<br/><span className="text-xs text-neutral-500">time</span></th>
              <th className="px-4 py-3 text-left font-medium">Question 1<br/><span className="text-xs text-neutral-500">Short text</span></th>
              <th className="px-4 py-3 text-left font-medium">Question 2<br/><span className="text-xs text-neutral-500">Long text</span></th>
              <th className="px-4 py-3 text-left font-medium">Question 3<br/><span className="text-xs text-neutral-500">Multiple choice</span></th>
              <th className="px-4 py-3 text-left font-medium">Question 4<br/><span className="text-xs text-neutral-500">File upload</span></th>
            </tr>
          </thead>
          <tbody>
            {Array.from({ length: 6 }, (_, i) => (
              <tr key={i} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="px-4 py-3"><input type="checkbox" /></td>
                <td className="px-4 py-3 text-neutral-600">name@example.com</td>
                <td className="px-4 py-3 text-neutral-600">1 APR 2026<br/>20:09</td>
                <td className="px-4 py-3 text-neutral-600">Lorem ipsum</td>
                <td className="px-4 py-3 text-neutral-600 max-w-[260px]">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,</td>
                <td className="px-4 py-3">
                  <div className="flex flex-wrap gap-1.5 max-w-[200px]">
                    {['Option 1', 'Option 2', 'Option 3', 'Option 4'].map(o => (
                      <span key={o} className="inline-flex items-center px-2 h-6 border border-neutral-200 rounded text-xs">{o}</span>
                    ))}
                  </div>
                </td>
                <td className="px-4 py-3 text-blue-600 underline">example.{i === 0 ? 'png' : 'mp4'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="flex items-center justify-between px-5 py-4">
        <span className="text-sm text-neutral-500">Showing 1-10 of 128</span>
        <Pagination />
      </div>
    </div>
  );
}

/* =================================================================
   FORM SETTINGS
   ================================================================= */
function FormSettingsPage() {
  return (
    <DashShell active="/app/forms">
      <div className="flex items-center justify-between mb-6">
        <Link to="/app/forms" className="inline-flex items-center gap-2 text-xl font-bold hover:text-neutral-700">
          <Icon name="chevronLeft" size={20} /> Settings
        </Link>
        <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} /> Save changes
        </button>
      </div>

      <h2 className="text-xl font-bold mb-1">Integrations</h2>
      <p className="text-sm text-neutral-500 mb-4">Save time and effort with these integrations for Typeform</p>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-10">
        <IntegrationCard color="#EBE0FF" title="ClickUp Integration" desc="Automatically send form responses to ClickUp" />
        <IntegrationCard color="#D6F3DC" title="Google Sheets Integration" desc="Send your responses directly to Google Sheets" />
      </div>

      <h2 className="text-xl font-bold mb-1">Coupons</h2>
      <p className="text-sm text-neutral-500 mb-4">Manage post-completion rewards</p>
      <div className="bg-white border border-neutral-200 rounded-xl p-5">
        <div className="w-10 h-10 rounded-lg bg-neutral-200 mb-12" />
        <h3 className="font-bold mb-1">Attach coupons</h3>
        <p className="text-sm text-neutral-500">-</p>
      </div>
    </DashShell>
  );
}

/* =================================================================
   USER FORM VIEW (recipient-facing)
   ================================================================= */
function UserFormViewPage({ slug = 'my-new-form', page = 'welcome' }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="grid grid-cols-1 lg:grid-cols-[220px_1fr] gap-6 px-6 py-6 max-w-[min(1800px,90vw)] mx-auto">
        <aside className="bg-white border border-neutral-200 rounded-2xl p-4 h-fit">
          <h3 className="font-bold mb-3">Pages</h3>
          <div className="space-y-2">
            {[
              { id: 'welcome', label: 'Welcome screen' },
              { id: 'basic', label: 'Basic info' },
              { id: 'survey', label: 'YSEALI Summit 2024 and Y…' },
            ].map(p => (
              <div key={p.id} className={`flex items-center justify-between px-3 h-10 rounded-lg border text-sm ${page === p.id ? 'bg-neutral-100 border-neutral-300 font-medium' : 'bg-white border-neutral-200'}`}>
                <span className="truncate">{p.label}</span>
                <button className="text-neutral-500 hover:text-neutral-900"><Icon name="more" size={14} /></button>
              </div>
            ))}
          </div>
        </aside>

        <div>
          {page === 'welcome' && <UserFormWelcome />}
          {page === 'basic' && <UserFormBasic />}
          {page === 'survey' && <UserFormSurvey />}
        </div>
      </div>
    </div>
  );
}

function UserFormWelcome() {
  return (
    <>
      <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[640px] flex flex-col items-center justify-center relative">
        <div className="absolute top-5 right-5 w-7 h-7"><MerekaLogo /></div>
        <h2 className="text-2xl font-bold mb-4">Pre-Summit Program Survey</h2>
        <p className="text-sm text-neutral-500 text-center max-w-2xl mb-8">
          Hi there! Please take a moment of your time to fill this survey up so that it helps us tailor the YSEALI Next ESC program at the upcoming YSEALI Summit 2024 in Luang Prabang, Laos.
        </p>
        <Link to="/app/form/user/my-new-form/basic">
          <button className="h-12 px-10 bg-neutral-900 text-white rounded-full font-semibold">Start</button>
        </Link>
      </div>
    </>
  );
}

function UserFormBasic() {
  return (
    <>
      <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[640px] relative">
        <div className="absolute top-5 right-5 w-7 h-7"><MerekaLogo /></div>
        <p className="text-xs font-bold uppercase tracking-wide mt-12">BASIC INFO</p>
        <p className="text-sm text-neutral-600 mb-8">Tell us about yourself!</p>
        <div className="space-y-8">
          <div className="flex items-start gap-3">
            <span className="text-neutral-500 text-sm mt-1.5">1</span>
            <div className="flex-1">
              <h3 className="text-lg mb-3">Tell us your name</h3>
              <input placeholder="Type your answer here..." className="w-full h-12 px-4 text-sm border border-neutral-200 rounded-lg" />
            </div>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-neutral-500 text-sm mt-1.5">2</span>
            <div className="flex-1">
              <h3 className="text-lg mb-3">Your email*</h3>
              <input placeholder="Type your answer here..." className="w-full h-12 px-4 text-sm border border-neutral-200 rounded-lg" />
            </div>
          </div>
        </div>
      </div>
      <UserFormFooter />
    </>
  );
}

function UserFormSurvey() {
  return (
    <>
      <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[640px] relative">
        <div className="absolute top-5 right-5 w-7 h-7"><MerekaLogo /></div>
        <p className="text-xs font-bold uppercase tracking-wide mt-16">YSEALI SUMMIT 2024 AND YSEALI NEXT ESC PROFESSIONAL &amp; PERSONEL DEVELOPMENT SE</p>
        <div className="mt-6 flex items-start gap-3">
          <span className="text-neutral-500 text-sm mt-1.5">1</span>
          <div className="flex-1">
            <h3 className="text-lg mb-1">What are you hoping to gain from the Summit and the YSEALI Next ESC Professional &amp; Personal Development Series?</h3>
            <p className="text-sm text-neutral-500 mb-4">Choose as many as you like.</p>
            <div className="space-y-2">
              <RadioRow2Text label="A - Expanding my professional network" />
              <RadioRow2Text label="B - Showcasing my small grand project" checked />
              <RadioRow2Text label="C - Learning new leadership skills" />
              <div className="flex items-center gap-2">
                <RadioRow2Text label={<>D - <span className="underline">other</span></>} checked />
              </div>
              <div className="flex items-center gap-2">
                <RadioRow2Text label={<span>D - <input placeholder="Type your answer here..." className="border-0 outline-0 ml-1 text-sm" /></span>} checked />
                <button className="w-7 h-7 border border-neutral-300 rounded-md inline-flex items-center justify-center text-neutral-500 hover:bg-neutral-50"><Icon name="check" size={14} /></button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <UserFormFooter />
    </>
  );
}

function UserFormFooter() {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl px-6 py-4 mt-4 flex items-center justify-between">
      <button className="h-11 px-6 border border-neutral-300 rounded-full text-sm font-semibold hover:bg-neutral-50">Back</button>
      <button className="h-11 px-8 bg-neutral-900 text-white rounded-full text-sm font-semibold hover:bg-neutral-800">Continue</button>
    </div>
  );
}

/* =================================================================
   DESIGN PANEL — standalone showcase
   ================================================================= */
function DesignPanelPage() {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="px-6 py-8 max-w-[min(1800px,90vw)] mx-auto">
        <h1 className="text-2xl font-bold mb-1">Design panel</h1>
        <p className="text-sm text-neutral-500 mb-8">Floating panel used inside the form builder for branding.</p>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <DesignPanelCard tab="logo" />
          <DesignPanelCard tab="button" />
          <DesignPanelCard tab="background" />
        </div>
      </div>
    </div>
  );
}

function DesignPanelCard({ tab }) {
  return (
    <div className="bg-white rounded-2xl border border-neutral-200 shadow-sm p-5">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <Icon name="menu" size={14} className="text-neutral-400 rotate-90" />
          <h3 className="font-bold">Design</h3>
        </div>
        <button className="text-neutral-500"><Icon name="close" size={16} /></button>
      </div>
      <div className="flex items-center gap-2 mb-5">
        {[
          { v: 'logo', l: 'Logo' },
          { v: 'button', l: 'Button' },
          { v: 'background', l: 'Background' },
        ].map(t => (
          <button key={t.v}
            className={`px-4 h-8 rounded-full text-sm border transition-colors ${tab === t.v ? 'bg-neutral-100 border-neutral-300 font-medium' : 'bg-white border-neutral-200 hover:bg-neutral-50'}`}>
            {t.l}
          </button>
        ))}
      </div>

      {tab === 'logo' && <LogoPanel />}
      {tab === 'button' && <ButtonPanel />}
      {tab === 'background' && <BackgroundPanel />}

      <div className="flex items-center gap-3 mt-6">
        <button className="flex-1 h-10 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Revert</button>
        <button className="flex-1 h-10 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">Save Changes</button>
      </div>
    </div>
  );
}

function LogoPanel() {
  return (
    <>
      <p className="text-sm font-bold mb-2">Logo</p>
      <button className="w-full h-10 px-3 border border-neutral-200 rounded-lg text-sm inline-flex items-center justify-between text-neutral-400 mb-4">
        JPG, PNG or GIF. Up to 4mb. <Icon name="upload" size={14} />
      </button>
      <p className="text-sm font-bold mb-2">Size</p>
      <div className="flex items-center gap-4 mb-4">
        {[
          { v: 'small', l: 'Small', c: true },
          { v: 'medium', l: 'Medium' },
          { v: 'large', l: 'Large' },
        ].map(s => (
          <label key={s.v} className="flex items-center gap-2 cursor-pointer">
            <span className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${s.c ? 'border-neutral-900' : 'border-neutral-400'}`}>
              {s.c && <span className="w-2 h-2 rounded-full bg-neutral-900" />}
            </span>
            <span className="text-sm">{s.l}</span>
          </label>
        ))}
      </div>
      <p className="text-sm font-bold mb-2">Alignment</p>
      <div className="flex items-center gap-4">
        {[
          { c: true, ic: '|≡' },
          { c: false, ic: '≡|' },
          { c: false, ic: '|≡|' },
        ].map((a, i) => (
          <label key={i} className="flex items-center gap-2 cursor-pointer">
            <span className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${a.c ? 'border-neutral-900' : 'border-neutral-400'}`}>
              {a.c && <span className="w-2 h-2 rounded-full bg-neutral-900" />}
            </span>
            <span className="text-sm font-mono">{a.ic}</span>
          </label>
        ))}
      </div>
    </>
  );
}

const SWATCHES = ['#000', '#1F6FEB', '#22C55E', '#FBBF24', '#EF4444', '#1F2937', '#9CA3AF'];

function ColorRow() {
  return (
    <div className="flex items-center gap-1.5 mb-2">
      <span className="w-6 h-6 rounded-full border border-neutral-300 inline-flex items-center justify-center"><Icon name="check" size={12} strokeWidth={3} /></span>
      {SWATCHES.slice(1).map((c, i) => (
        <span key={i} className="w-6 h-6 rounded-full" style={{ background: c }} />
      ))}
      <button className="w-6 h-6 rounded-full border border-neutral-300 flex items-center justify-center text-neutral-500"><Icon name="plus" size={12} /></button>
    </div>
  );
}

function HexInput({ value = '#000000' }) {
  return (
    <div className="relative mb-4">
      <input defaultValue={value} className="w-full h-9 pl-3 pr-16 text-sm border border-neutral-200 rounded-lg bg-neutral-50 text-neutral-500" />
      <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1.5">
        <span className="w-5 h-5 rounded-full border border-neutral-300" />
        <Icon name="edit" size={12} className="text-neutral-500" />
      </div>
    </div>
  );
}

function ButtonPanel() {
  return (
    <>
      <p className="text-sm font-bold mb-2">Button color</p>
      <ColorRow />
      <HexInput />
      <p className="text-sm font-bold mb-2">Button text color</p>
      <ColorRow />
      <HexInput />
      <p className="text-sm font-bold mb-2">Answer color</p>
      <ColorRow />
      <HexInput />
    </>
  );
}

function BackgroundPanel() {
  return (
    <>
      <p className="text-sm font-bold mb-2">Color</p>
      <ColorRow />
      <HexInput />
      <p className="text-sm font-bold mb-2">Upload image</p>
      <button className="w-full h-10 px-3 border border-neutral-200 rounded-lg text-sm inline-flex items-center justify-between text-neutral-400">
        JPG, PNG or GIF. Up to 4mb. <Icon name="upload" size={14} />
      </button>
    </>
  );
}


/* ===== Booking Details full page ===== */
function BookingDetailsPage({ id = 'b1' }) {
  const g = (typeof BOOKING_ATTENDEES !== 'undefined' && BOOKING_ATTENDEES.find(a => a.id === id)) || { name: 'Mathialagi', email: 'kmathialagi@gmail.com', contact: '+60175578162', tickets: '1x' };
  const link = 'https://biji-biji.zoom.us/j/82301144216';
  return (
    <DashShell active="/app/hub/services/experiences">
      <div className="max-w-[880px]">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <button onClick={() => history.back()} className="w-9 h-9 rounded-full border border-neutral-200 flex items-center justify-center text-neutral-700 hover:bg-neutral-50"><Icon name="chevronLeft" size={18} /></button>
            <h1 className="text-3xl font-bold text-neutral-900" style={{ fontFamily: _pp }}>Booking Details</h1>
          </div>
          <button className="w-10 h-10 rounded-full flex items-center justify-center text-neutral-600 hover:bg-neutral-100" title="Print"><Icon name="document" size={20} /></button>
        </div>
        <div className="border-t border-neutral-200 pt-6">
          <p className="text-sm text-neutral-600">Jul 18, 2026, 9:00 AM - 5:00 PM (MYT) <span className="mx-2 text-neutral-300">|</span> Confirmation Code: <span className="font-semibold text-neutral-800">0MOXUB9DZbaXlZmclSAG</span></p>
          <h2 className="mt-2 text-2xl font-bold text-neutral-900 inline-flex items-center gap-2" style={{ fontFamily: _pp }}>
            <Link to="/web/learning-paths/fluency" className="hover:underline">[AI4U] AI Fluency: Master the Skills That Matter</Link> <Icon name="external" size={18} className="text-neutral-500" />
          </h2>
          <div className="mt-2 flex items-center gap-2 text-sm text-neutral-600"><Icon name="globe" size={15} className="text-neutral-500" /> Online <span className="text-neutral-300">|</span> Host: Amyra Efasyafiqa Binti Lismawira Amraf</div>
        </div>
        <div className="border-t border-neutral-200 mt-6 pt-6 flex items-center justify-between gap-4 flex-wrap">
          <p className="text-sm"><span className="font-bold text-neutral-900">Link to Online Experience:</span> <a href={link} className="text-blue-600 underline break-all">{link}</a></p>
          <CopyButton text={link} label="Copy Link" icon={null} className="h-10 px-5 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50" />
        </div>
        <div className="border-t border-neutral-200 mt-6 pt-6">
          <h3 className="text-xl font-bold text-neutral-900 mb-4" style={{ fontFamily: _pp }}>Guests &amp; Tickets</h3>
          <p className="font-bold text-neutral-900">{g.tickets || '1x'} Get AI Ready!</p>
          <p className="font-bold text-neutral-900 mt-3">{g.name}</p>
          <p className="text-sm text-neutral-500">{g.email} <span className="mx-1 text-neutral-300">|</span> {g.contact}</p>
        </div>
        <div className="border-t border-neutral-200 mt-6 pt-6 mb-10">
          <h3 className="text-xl font-bold text-neutral-900" style={{ fontFamily: _pp }}>Payment Breakdown</h3>
          <p className="text-sm font-bold text-neutral-800 mt-1 mb-4">Status: FREE</p>
          {[['1 x Get AI Ready!', 'Price per Get AI Ready!', 'FREE'], ['Service Fee (Paid by User)', '', 'FREE']].map((r, i) => (
            <div key={i} className="flex items-center justify-between py-3 border-b border-neutral-100">
              <div><div className="text-sm font-medium text-neutral-800">{r[0]}</div>{r[1] && <div className="text-xs text-neutral-400 mt-0.5">{r[1]}</div>}</div>
              <div className="text-sm font-semibold text-neutral-800">{r[2]}</div>
            </div>
          ))}
          <div className="flex items-center justify-between py-4 font-bold text-neutral-900"><span>Total</span><span>FREE</span></div>
        </div>
      </div>
    </DashShell>
  );
}

Object.assign(window, {
  UserOverviewPageV2,
  ManageFormsPage, FormSettingsPage,
  FormBuilderContentPage, FormBuilderConnectPage, FormBuilderSharePage, FormBuilderResultsPage,
  UserFormViewPage, DesignPanelPage,
  MyCoursesDashPage, MyPurchasesDashPage, MyProgrammesDashPage, MyGigsDashPage,
  MyExperiencesDashPage, MyExpertiseDashPage,
  ManageCommunicationsDashPage, AnalyticsDashPage,
  ManageListingsDashPage, ManageGigsDashPage, ManageProgramsDashPage, BookingDetailsPage,
  PostListingPage,
  DashShell, DashHeader, Pagination,
});

/* ===== Post Listing (type picker) ===== */
const LISTING_TYPES = [
  {
    id: 'experience',
    title: 'Experience',
    icon: (
      <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true">
        <path d="M28 10c-6 0-11 5-11 11 0 4 2 8 6 10v6h-4v6h4l-2 14h14l-2-14h4v-6h-4v-6c4-2 6-6 6-10 0-6-5-11-11-11Z"/>
      </svg>
    ),
    desc: 'Host a virtual or physical Experience and share your passion with thousands of Learners!',
    to: '/app/onboarding/experience/select-type',
  },
  {
    id: 'expertise',
    title: 'Expertise',
    icon: (
      <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true">
        <path d="M44 18a14 14 0 1 0-22 11v9a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4v-9a14 14 0 0 0 2-11Zm-12 38a4 4 0 0 0 4-4h-8a4 4 0 0 0 4 4Z"/>
        <circle cx="42" cy="14" r="6" fill="#fff"/>
        <path d="M42 10a4 4 0 1 1-4 4 4 4 0 0 1 4-4Zm-1.5 6.5 2.5 2.5 4-4-1-1-3 3-1.5-1.5Z"/>
      </svg>
    ),
    desc: 'Allow users to sign up for one on one sessions with you, to share your knowledge with the world!',
    to: '/app/onboarding/expertise/brief',
  },
  {
    id: 'gigs',
    title: 'Gigs',
    icon: (
      <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true">
        <path d="M18 22h28a4 4 0 0 1 4 4v22a4 4 0 0 1-4 4H18a4 4 0 0 1-4-4V26a4 4 0 0 1 4-4Z"/>
        <path d="M26 18v-4a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v4" fill="none" stroke="currentColor" strokeWidth="4"/>
        <rect x="28" y="32" width="8" height="4" rx="1" fill="#fff"/>
      </svg>
    ),
    desc: 'Post short-term work, projects or contracts and connect with vetted Experts to get them done.',
    to: '/app/onboarding/job/details',
  },
  {
    id: 'courses',
    title: 'Courses',
    icon: (
      <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true">
        <path d="M32 8 4 20l28 12 22-9.43V40h4V20Z"/>
        <path d="M14 28v12c0 4 8 8 18 8s18-4 18-8V28l-18 8Z"/>
      </svg>
    ),
    desc: 'Build a self-paced course with lessons, quizzes and certificates that learners can complete on their own time.',
    to: '/app/forms/builder/new/content',
  },
];

function PostListingPage() {
  return (
    <DashShell active="/app/post-listing">
      <DashHeader title="Post a listing" subtitle="Pick the type of listing you want to add to your hub." />
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-5">
        {LISTING_TYPES.map(t => (
          <Link key={t.id} to={t.to}
            className="group bg-white border border-neutral-200 rounded-2xl p-7 hover:border-neutral-900 transition-colors flex flex-col">
            <div className="text-neutral-900 mb-8">{t.icon}</div>
            <h3 className="text-lg font-bold mb-2">{t.title}</h3>
            <p className="text-sm text-neutral-700 leading-relaxed flex-1">{t.desc}</p>
            <span className="mt-6 inline-flex items-center gap-1 text-sm font-semibold text-blue-500 opacity-0 group-hover:opacity-100 transition-opacity">
              Get started <Icon name="arrowRight" size={14} />
            </span>
          </Link>
        ))}
      </div>
    </DashShell>
  );
}

/* =================================================================
   DASH-SHELL VERSIONS OF SIDEBAR-LINKED PAGES
   ================================================================= */

function DashHeader({ 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>
  );
}

/* ===== My Gigs (personal job applications) ===== */
function MyGigsDashPage() {
  const [tab, setTab] = useState('Proposed');
  const proposed = [
    { id: 'AP-318', job: 'Brand Identity for D2C Skincare Launch', client: 'Lumi Botanicals', bid: 'RM 8,500', status: 'Shortlisted', date: 'Submitted May 16' },
    { id: 'AP-312', job: 'Investor Deck — Series A', client: 'Stealth (FoodTech)', bid: 'RM 4,200', status: 'Under review', date: 'Submitted May 12' },
    { id: 'AP-305', job: 'Frontend Developer (Angular)', client: 'Hauz Capital', bid: 'RM 120 / hr', status: 'Interview', date: 'Submitted May 9' },
  ];
  const contracted = [
    { id: 'CT-088', job: 'Video Producer — Docu-Series', client: 'Yayasan Hijau', bid: 'RM 12,000', status: 'In progress', date: 'Started Apr 28' },
    { id: 'CT-081', job: 'Growth Consultant Retainer', client: 'Tumbuh App', bid: 'RM 6,000 / mo', status: 'Completed', date: 'Ended Mar 30' },
  ];
  const tone = { Shortlisted: 'info', 'Under review': 'warning', Interview: 'purple', 'In progress': 'success', Completed: 'neutral' };
  const rows = tab === 'Proposed' ? proposed : contracted;
  return (
    <DashShell active="/app/dashboard/gigs">
      <DashHeader title="My Gigs" subtitle="Proposals you've sent and gigs you've been contracted for."
        action={<Link to="/web/jobs"><button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50">Browse jobs <Icon name="search" size={14} /></button></Link>}
      />
      <div className="flex items-center gap-2 mb-5">
        {['Contracted', 'Proposed'].map(t => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-4 h-9 rounded-full text-sm font-medium transition-colors ${tab === t ? 'bg-neutral-900 text-white' : 'bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50'}`}>
            {t}
          </button>
        ))}
      </div>
      {rows.length === 0 ? (
        <div className="bg-white border border-neutral-200 rounded-2xl py-16 px-6 text-center">
          <div className="w-16 h-16 rounded-full bg-neutral-100 flex items-center justify-center mx-auto mb-5"><Icon name="search" size={26} className="text-neutral-400" /></div>
          <h3 className="text-xl font-bold mb-2">Let's get started!</h3>
          <p className="text-sm text-neutral-500 max-w-md mx-auto mb-6">You haven't sent any proposals or been contracted yet. Take a look at gigs that match your skills and start applying.</p>
          <Link to="/web/jobs"><button className="h-10 px-5 bg-neutral-900 text-white rounded-full text-sm font-semibold hover:bg-neutral-800">Browse jobs</button></Link>
        </div>
      ) : (
        <div className="space-y-3">
          {rows.map(r => (
            <div key={r.id} className="bg-white border border-neutral-200 rounded-2xl p-5">
              <div className="flex items-start justify-between gap-4 flex-wrap">
                <div className="flex-1 min-w-[260px]">
                  <div className="flex items-center gap-2 mb-2">
                    <Badge tone={tone[r.status]}>{r.status}</Badge>
                    <span className="font-mono text-xs text-neutral-400">{r.id}</span>
                  </div>
                  <h3 className="font-semibold">{r.job}</h3>
                  <p className="text-sm text-neutral-500 mt-1">{r.client} · {r.date}</p>
                </div>
                <div className="text-right flex-shrink-0">
                  <div className="text-lg font-bold num-tabular">{r.bid}</div>
                  <div className="text-xs text-neutral-500">{tab === 'Proposed' ? 'your bid' : 'contract value'}</div>
                  <button className="mt-3 h-9 px-4 border border-neutral-300 rounded-full text-sm font-semibold inline-flex items-center gap-1.5 hover:bg-neutral-50">View <Icon name="arrowRight" size={12} /></button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </DashShell>
  );
}

/* ===== My Programmes ===== */
/* Shared dashboard filter chips + "For You" recommendations — Figma 5289-48033/48538/48720/48884 */
function DashChips({ chips, value, onChange }) {
  const [a, setA] = useState(chips[0]);
  const active = value !== undefined ? value : a;
  const pick = onChange || setA;
  return (
    <div className="flex items-center gap-2.5 mb-5 flex-wrap">
      {chips.map(c => (
        <button key={c} onClick={() => pick(c)}
          className={`px-4 h-9 rounded-full text-[13px] font-medium border transition-colors ${active === c ? 'bg-neutral-900 text-white border-neutral-900' : 'bg-white text-neutral-600 border-neutral-200 hover:bg-neutral-50'}`}>
          {c}
        </button>
      ))}
    </div>
  );
}

/* status vs chip matcher: "All*" = everything, "Completed" = completed only, else = not completed */
function matchChip(status, chip) {
  if (!chip || chip.indexOf('All') === 0) return true;
  if (chip === 'Completed') return status === 'Completed';
  return status !== 'Completed';
}

/* Reusable search + sort toolbar for dashboard list pages */
function DashToolbar({ q, setQ, sort, setSort, sorts, placeholder }) {
  return (
    <div className="flex items-center justify-between gap-3 mb-5 flex-wrap">
      <div className="relative w-[280px] max-w-full">
        <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
        <input value={q} onChange={e => setQ(e.target.value)} placeholder={placeholder || 'Search...'}
          className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" />
      </div>
      {sorts && (
        <select value={sort} onChange={e => setSort(e.target.value)}
          className="h-10 px-3 rounded-full border border-neutral-200 bg-white text-sm text-neutral-800">
          {sorts.map(o => <option key={o} value={o}>Sort: {o}</option>)}
        </select>
      )}
    </div>
  );
}

function DashNoResults({ label = 'results' }) {
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl py-14 px-6 text-center">
      <div className="w-12 h-12 rounded-full bg-neutral-100 grid place-items-center mx-auto mb-3"><Icon name="search" size={20} className="text-neutral-400" /></div>
      <p className="text-sm font-semibold text-neutral-900">No {label} found</p>
      <p className="text-sm text-neutral-500 mt-1">Try a different search or filter.</p>
    </div>
  );
}

const FOR_YOU_RECS = [
  { tag: 'Programme', title: 'AI Fluency by Microsoft', meta: 'Mereka • 7 modules', price: '$49 / month', hue: 290 },
  { tag: 'Course', title: 'Microsoft Copilot for Beginners', meta: 'Mereka • 12 lessons', price: 'FREE', hue: 25 },
  { tag: 'Expertise', title: 'Boosting Sales and Productivity', meta: 'Studio Kuala', price: 'from RM 8,500', hue: 210 },
];
function ForYouGrid({ title = 'For You' }) {
  return (
    <div className="mt-10">
      <h2 className="text-xl font-bold mb-4">{title}</h2>
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {FOR_YOU_RECS.map((r, i) => (
          <div key={i} className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <div className="aspect-[16/9] relative" style={{ background: `linear-gradient(135deg, oklch(0.84 0.10 ${r.hue}), oklch(0.68 0.15 ${r.hue + 30}))` }}>
              <span className="absolute top-3 left-3 px-3 h-7 inline-flex items-center rounded-full text-xs font-semibold bg-white/85 text-neutral-700">{r.tag}</span>
            </div>
            <div className="p-5">
              <h3 className="font-bold text-base">{r.title}</h3>
              <p className="text-xs text-neutral-500 mt-1">{r.meta}</p>
              <div className="mt-4 flex items-center justify-between">
                <span className="font-bold text-sm">{r.price}</span>
                <button className="h-9 px-4 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">View</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MyProgrammesDashPage() {
  const programmes = [
    { t: 'AI Fundamentals for Teams', hub: 'Mereka Programs', meta: 'Module 1 of 6 · Intro to LLMs', p: 8, status: 'In progress', cta: 'Continue', cert: true, hue: 290, owner: 'Mereka Programs', focus: ['Applied AI', 'Teams'], duration: '6 weeks', cohorts: 3, enrolled: 420, rating: 4.6 },
    { t: 'Mereka Career Accelerator', hub: 'Biji-biji Initiative', meta: 'Module 4 of 8 · Personal branding', p: 52, status: 'In progress', cta: 'Continue', cert: true, hue: 25, owner: 'Biji-biji Initiative', focus: ['Career', 'Employability'], duration: '8 weeks', cohorts: 5, enrolled: 890, rating: 4.7 },
    { t: 'Dynamous AI Mastery', hub: 'Biji-biji Initiative', meta: 'Completed · Certificate issued', p: 100, status: 'Completed', cta: 'View certificate', cert: true, hue: 220, owner: 'Biji-biji Initiative', focus: ['Finance', 'Automation'], duration: '8 weeks', cohorts: 4, enrolled: 640, rating: 4.8 },
    { t: 'Design Leadership Program', hub: 'Studio Kuala', meta: 'Not started · 10 modules', p: 0, status: 'Enrolled', cta: 'Start learning', cert: true, hue: 160, owner: 'Studio Kuala', focus: ['Design', 'Leadership'], duration: '10 weeks', cohorts: 2, enrolled: 210, rating: 4.5 },
  ];
  const goProg = (p) => setProg({ name: p.t, owner: p.owner, focus: p.focus, status: p.status, duration: p.duration, cohorts: p.cohorts, enrolled: p.enrolled, completion: p.p, rating: p.rating });
  const [q, setQ] = useState(''); const [chip, setChip] = useState('All Programmes'); const [sort, setSort] = useState('Default');
  let view = programmes.filter(p => matchChip(p.status, chip) && (q === '' || (p.t + ' ' + p.hub).toLowerCase().includes(q.toLowerCase())));
  if (sort === 'Progress') view = [...view].sort((a, b) => b.p - a.p);
  else if (sort === 'Name A–Z') view = [...view].sort((a, b) => a.t.localeCompare(b.t));
  const tone = { 'In progress': 'bg-blue-50 text-blue-600', Completed: 'bg-green-50 text-green-600', Enrolled: 'bg-neutral-100 text-neutral-500' };
  return (
    <DashShell active="/app/dashboard/programmes">
      <DashHeader title={`My Programmes (${programmes.length})`} subtitle="Multi-course learning paths you're enrolled in."
        action={<Link to="/web/learning-paths"><button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50">Browse programmes <Icon name="search" size={14} /></button></Link>}
      />
      <DashChips chips={['All Programmes', 'In Progress', 'Completed']} value={chip} onChange={setChip} />
      <DashToolbar q={q} setQ={setQ} sort={sort} setSort={setSort} sorts={['Default', 'Progress', 'Name A–Z']} placeholder="Search programmes..." />
      {view.length === 0 ? <DashNoResults label="programmes" /> : (
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {view.map((p, i) => (
          <div key={i} className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <div className="aspect-[16/9] relative" style={{ background: `linear-gradient(135deg, oklch(0.84 0.10 ${p.hue}), oklch(0.68 0.15 ${p.hue + 30}))` }}>
              <span className={`absolute top-3 left-3 px-3 h-7 inline-flex items-center rounded-full text-xs font-semibold ${tone[p.status]}`}>{p.status}</span>
              {p.cert && <span className="absolute top-3 right-3 px-3 h-7 inline-flex items-center gap-1 rounded-full text-xs font-semibold bg-white/85 text-neutral-700"><Icon name="award" size={13} /> Certificate</span>}
            </div>
            <div className="p-5">
              <Link to="/app/program/admin/overview/learner" onClick={() => goProg(p)}><h3 className="font-bold text-base hover:text-blue-600 transition-colors cursor-pointer">{p.t}</h3></Link>
              <p className="text-xs text-neutral-500 mt-1">{p.hub}</p>
              <Progress value={p.p} className="mt-4" />
              <div className="mt-2 flex items-center justify-between text-xs">
                <span className="text-neutral-500">{p.meta}</span>
                <span className="font-semibold num-tabular">{p.p}%</span>
              </div>
              <Link to="/app/program/admin/overview/learner" className="block mt-4" onClick={() => goProg(p)}><button className="w-full h-10 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">{p.cta}</button></Link>
            </div>
          </div>
        ))}
      </div>)}
      <ForYouGrid />
    </DashShell>
  );
}

/* ===== My Courses ===== */
function MyCoursesDashPage() {
  const courses = [
    { t: 'Brand Identity Sprint', hub: 'Studio Kuala', mod: 'Module 3 of 6 · Positioning', p: 48, hue: 275 },
    { t: 'Digital Illustration Bootcamp', hub: 'Pixel House', mod: 'Lesson 5 of 18 · Colour theory', p: 28, hue: 220 },
    { t: 'Sustainable Cooking Masterclass', hub: 'Chef Aisyah Lim', mod: 'Lesson 2 of 8 · Sourcing', p: 12, hue: 140 },
    { t: 'AI Fundamentals for Teams', hub: 'Mereka Programs', mod: 'Week 1 of 6 · Intro to LLMs', p: 8, hue: 290 },
  ];
  const [q, setQ] = useState(''); const [chip, setChip] = useState('All Courses'); const [sort, setSort] = useState('Default');
  let view = courses.filter(c => matchChip(c.p >= 100 ? 'Completed' : 'In progress', chip) && (q === '' || (c.t + ' ' + c.hub).toLowerCase().includes(q.toLowerCase())));
  if (sort === 'Progress') view = [...view].sort((a, b) => b.p - a.p);
  else if (sort === 'Name A–Z') view = [...view].sort((a, b) => a.t.localeCompare(b.t));
  return (
    <DashShell active="/app/dashboard/courses">
      <DashHeader title={`My Courses (${courses.length})`} subtitle="Pick up where you left off."
        action={<Link to="/web/courses"><button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50">Browse catalog <Icon name="search" size={14} /></button></Link>}
      />
      <DashChips chips={['All Courses', 'In Progress', 'Completed']} value={chip} onChange={setChip} />
      <DashToolbar q={q} setQ={setQ} sort={sort} setSort={setSort} sorts={['Default', 'Progress', 'Name A–Z']} placeholder="Search courses..." />
      {view.length === 0 ? <DashNoResults label="courses" /> : (
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {view.map((c, i) => (
          <div key={i} className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <div className="aspect-[16/9]" style={{ background: `linear-gradient(135deg, oklch(0.84 0.10 ${c.hue}), oklch(0.68 0.15 ${c.hue + 30}))` }} />
            <div className="p-5">
              <h3 className="font-bold text-base">{c.t}</h3>
              <p className="text-xs text-neutral-500 mt-1">{c.hub}</p>
              <Progress value={c.p} className="mt-4" />
              <div className="mt-2 flex items-center justify-between text-xs">
                <span className="text-neutral-500">{c.mod}</span>
                <span className="font-semibold num-tabular">{c.p}%</span>
              </div>
              <button className="w-full mt-4 h-10 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">Continue learning</button>
            </div>
          </div>
        ))}
      </div>)}
      <ForYouGrid />
    </DashShell>
  );
}

/* ===== My Experiences ===== */
function MyExperiencesDashPage() {
  const experiences = [
    { t: 'Traditional Batik Painting Workshop', slug: 'kuala-lumpur-batik-workshop', hub: 'Kraf KL Studio', meta: '25 May 2026 · 3:00 PM', loc: 'Bangsar, Kuala Lumpur', status: 'Upcoming', cta: 'View details', hue: 25 },
    { t: 'Pottery Wheel Throwing for Beginners', slug: 'pottery-wheel-throwing', hub: 'Tanah Liat Studio', meta: '02 Jun 2026 · 10:00 AM', loc: 'Subang Jaya', status: 'Upcoming', cta: 'View details', hue: 30 },
    { t: 'Tropical Garden Walking Tour', slug: 'tropical-garden-tour', hub: 'Greenhaus Hub', meta: '18 Apr 2026 · 9:00 AM', loc: 'Genting Highlands', status: 'Completed', cta: 'View details', hue: 170 },
    { t: 'Sourdough Bread Baking Class', slug: 'sourdough-bread-class', hub: 'Mill & Crust', meta: '10 Mar 2026 · 2:00 PM', loc: 'Damansara', status: 'Completed', cta: 'View details', hue: 35 },
  ];
  const tone = { Upcoming: 'bg-blue-50 text-blue-600', Completed: 'bg-neutral-100 text-neutral-500' };
  const [q, setQ] = useState(''); const [chip, setChip] = useState('All'); const [sort, setSort] = useState('Default');
  let view = experiences.filter(e => matchChip(e.status, chip) && (q === '' || (e.t + ' ' + e.hub + ' ' + e.loc).toLowerCase().includes(q.toLowerCase())));
  if (sort === 'Name A–Z') view = [...view].sort((a, b) => a.t.localeCompare(b.t));
  return (
    <DashShell active="/app/dashboard/bookings">
      <DashHeader title={`My Experiences (${experiences.length})`} subtitle="Workshops, tours and sessions you've booked."
        action={<Link to="/web/experiences"><button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50">Browse experiences <Icon name="search" size={14} /></button></Link>}
      />
      <DashChips chips={['All', 'Upcoming', 'Completed']} value={chip} onChange={setChip} />
      <DashToolbar q={q} setQ={setQ} sort={sort} setSort={setSort} sorts={['Default', 'Name A–Z']} placeholder="Search your experiences..." />
      {view.length === 0 ? <DashNoResults label="experiences" /> : (
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {view.map((e, i) => (
          <div key={i} className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <div className="aspect-[16/9] relative" style={{ background: `linear-gradient(135deg, oklch(0.84 0.10 ${e.hue}), oklch(0.68 0.15 ${e.hue + 30}))` }}>
              <span className={`absolute top-3 left-3 px-3 h-7 inline-flex items-center rounded-full text-xs font-semibold ${tone[e.status]}`}>{e.status}</span>
            </div>
            <div className="p-5">
              <h3 className="font-bold text-base">{e.t}</h3>
              <p className="text-xs text-neutral-500 mt-1">{e.hub}</p>
              <div className="mt-4 space-y-1.5">
                <p className="text-sm text-neutral-700 flex items-center gap-2"><Icon name="calendar" size={14} className="text-neutral-400" /> {e.meta}</p>
                <p className="text-sm text-neutral-500 flex items-center gap-2"><Icon name="pin" size={14} className="text-neutral-400" /> {e.loc}</p>
              </div>
              <Link to={`/web/experiences/${e.slug}`} className="block mt-4"><button className="w-full h-10 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">{e.cta}</button></Link>
            </div>
          </div>
        ))}
      </div>)}
      <ForYouGrid />
    </DashShell>
  );
}

/* ===== My Expertise ===== */
function MyExpertiseDashPage() {
  const expertise = [
    { t: 'Brand Identity Sprint — 2 weeks', slug: 'brand-identity-sprint', expert: 'Studio Kuala', meta: 'Online + 1 in-person · 2 weeks', when: '28 May 2026 · 4:00 PM', status: 'Upcoming', cta: 'View details', hue: 275 },
    { t: 'UX Audit & Roadmap', slug: 'ux-audit-roadmap', expert: 'Pixel House', meta: 'Remote · 1–2 weeks', when: '05 Jun 2026 · 11:00 AM', status: 'Scheduled', cta: 'View details', hue: 220 },
    { t: 'Content Engine Playbook', slug: 'content-engine-playbook', expert: 'Frame & Field', meta: 'Online · 3 weeks', when: '12 Apr 2026', status: 'Completed', cta: 'View details', hue: 340 },
    { t: 'Growth Diagnostic + Plan', slug: 'growth-diagnostic-plan', expert: 'Loop Growth', meta: 'Remote · 2 weeks', when: '02 Mar 2026', status: 'Completed', cta: 'View details', hue: 290 },
  ];
  const tone = { Upcoming: 'bg-green-50 text-green-600', Scheduled: 'bg-blue-50 text-blue-600', Completed: 'bg-neutral-100 text-neutral-500' };
  const [q, setQ] = useState(''); const [chip, setChip] = useState('All'); const [sort, setSort] = useState('Default');
  let view = expertise.filter(e => matchChip(e.status, chip) && (q === '' || (e.t + ' ' + e.expert).toLowerCase().includes(q.toLowerCase())));
  if (sort === 'Name A–Z') view = [...view].sort((a, b) => a.t.localeCompare(b.t));
  return (
    <DashShell active="/app/dashboard/reviews">
      <DashHeader title={`Expertise sessions (${expertise.length})`} subtitle="1-on-1 expert sessions you've booked."
        action={<Link to="/web/experts"><button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50">Find experts <Icon name="search" size={14} /></button></Link>}
      />
      <DashChips chips={['All', 'Upcoming', 'Completed']} value={chip} onChange={setChip} />
      <DashToolbar q={q} setQ={setQ} sort={sort} setSort={setSort} sorts={['Default', 'Name A–Z']} placeholder="Search your expertise..." />
      {view.length === 0 ? <DashNoResults label="sessions" /> : (
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {view.map((e, i) => (
          <div key={i} className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <div className="aspect-[16/9] relative flex items-center justify-center" style={{ background: `linear-gradient(135deg, oklch(0.84 0.10 ${e.hue}), oklch(0.68 0.15 ${e.hue + 30}))` }}>
              <span className={`absolute top-3 left-3 px-3 h-7 inline-flex items-center rounded-full text-xs font-semibold ${tone[e.status]}`}>{e.status}</span>
              <div className="w-20 h-20 rounded-full ring-4 ring-white/40 overflow-hidden"><Avatar name={e.expert} size={80} /></div>
            </div>
            <div className="p-5">
              <h3 className="font-bold text-base">{e.t}</h3>
              <p className="text-xs text-neutral-500 mt-1">by {e.expert}</p>
              <div className="mt-4 space-y-1.5">
                <p className="text-sm text-neutral-700 flex items-center gap-2"><Icon name="clock" size={14} className="text-neutral-400" /> {e.meta}</p>
                <p className="text-sm text-neutral-500 flex items-center gap-2"><Icon name="calendar" size={14} className="text-neutral-400" /> {e.when}</p>
              </div>
              <Link to={`/web/expertise/${e.slug}`} className="block mt-4"><button className="w-full h-10 bg-neutral-900 text-white rounded-lg text-sm font-semibold hover:bg-neutral-800">{e.cta}</button></Link>
            </div>
          </div>
        ))}
      </div>)}
      <ForYouGrid />
    </DashShell>
  );
}

/* ===== My Purchases ===== */
function MyPurchasesDashPage() {
  const [tab, setTab] = useState('All');
  const purchases = [
    { id: 'P-2851', desc: 'UX Audit session — Rafael Tan', date: 'May 18, 2026', amt: 'RM 420.00', kind: 'Booking', status: 'Paid' },
    { id: 'P-2812', desc: 'Sourdough Bread Class', date: 'May 14, 2026', amt: 'RM 210.00', kind: 'Booking', status: 'Paid' },
    { id: 'P-2790', desc: 'Brand Identity Sprint — Milestone 1', date: 'May 8, 2026', amt: 'RM 2,800.00', kind: 'Milestone', status: 'Paid' },
    { id: 'P-2772', desc: 'AI Fundamentals — Program enrolment', date: 'May 1, 2026', amt: 'RM 1,200.00', kind: 'Program', status: 'Paid' },
    { id: 'P-2733', desc: 'Pottery refund', date: 'Apr 28, 2026', amt: '-RM 150.00', kind: 'Refund', status: 'Refunded' },
  ];
  const filtered = tab === 'All' ? purchases : purchases.filter(p => p.kind === tab);
  return (
    <DashShell active="/app/dashboard/billing">
      <DashHeader title="My Purchases" subtitle="All your bookings, programs, and milestone payments."
        action={<button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50"><Icon name="download" size={14} /> Export CSV</button>}
      />
      <div className="flex items-center gap-2 mb-5 flex-wrap">
        {['All', 'Booking', 'Program', 'Milestone', 'Refund'].map(f => (
          <button key={f} onClick={() => setTab(f)}
            className={`px-4 h-8 rounded-full text-sm transition-colors ${tab === f ? 'bg-neutral-900 text-white font-semibold' : 'bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50'}`}>
            {f}
          </button>
        ))}
      </div>
      <div className="bg-white border border-neutral-200 rounded-2xl overflow-x-auto">
        <table className="w-full text-sm min-w-[760px]">
          <thead>
            <tr className="border-b border-neutral-100 text-neutral-500">
              <th className="text-left px-5 py-3 font-medium">Reference</th>
              <th className="text-left px-5 py-3 font-medium">Description</th>
              <th className="text-left px-5 py-3 font-medium">Date</th>
              <th className="text-left px-5 py-3 font-medium">Type</th>
              <th className="text-right px-5 py-3 font-medium">Amount</th>
              <th className="text-left px-5 py-3 font-medium">Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr><td colSpan={6} className="px-5 py-12 text-center text-sm text-neutral-500">No purchases match this filter.</td></tr>
            ) : filtered.map(p => (
              <tr key={p.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="px-5 py-3 font-mono text-xs text-neutral-500">{p.id}</td>
                <td className="px-5 py-3 font-medium">{p.desc}</td>
                <td className="px-5 py-3 text-neutral-600">{p.date}</td>
                <td className="px-5 py-3"><Badge tone="neutral">{p.kind}</Badge></td>
                <td className="px-5 py-3 text-right font-semibold num-tabular">{p.amt}</td>
                <td className="px-5 py-3"><Badge tone={p.status === 'Paid' ? 'success' : 'info'}>{p.status}</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </DashShell>
  );
}

/* ===== Manage Communications ===== */
function ManageCommunicationsDashPage() {
  const [ch, setCh] = useState('All');
  const [search, setSearch] = useState('');
  const logs = [
    { id: 'C-9012', ch: 'Email', sub: 'Your sourdough class is confirmed', to: 'faiz.fadhillah@example.com', date: 'May 18 12:42 PM', status: 'Delivered' },
    { id: 'C-9011', ch: 'WhatsApp', sub: 'Reminder: UX session in 24h', to: '+60 12 345 6789', date: 'May 17 3:00 PM', status: 'Delivered' },
    { id: 'C-9008', ch: 'Email', sub: 'Receipt — Brand Identity Sprint M1', to: 'faiz.fadhillah@example.com', date: 'May 8 9:14 AM', status: 'Delivered' },
    { id: 'C-9006', ch: 'Email', sub: 'Welcome to AI Fundamentals', to: 'faiz.fadhillah@example.com', date: 'May 1 8:00 AM', status: 'Delivered' },
    { id: 'C-9001', ch: 'SMS', sub: 'Login code: 482 109', to: '+60 12 345 6789', date: 'Apr 30 9:55 PM', status: 'Delivered' },
    { id: 'C-8998', ch: 'Email', sub: 'Profile incomplete reminder', to: 'faiz.fadhillah@example.com', date: 'Apr 28 10:02 AM', status: 'Bounced' },
  ];
  const filtered = logs.filter(l =>
    (ch === 'All' || l.ch === ch) &&
    (search === '' || (l.sub + ' ' + l.to).toLowerCase().includes(search.toLowerCase()))
  );
  const tone = { Email: 'info', WhatsApp: 'success', SMS: 'purple' };
  return (
    <DashShell active="/app/dashboard/communication-logs">
      <DashHeader title="Manage Communications" subtitle="Every email, WhatsApp and SMS sent on your behalf."
        action={<button className="h-10 px-4 bg-neutral-900 text-white rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-800"><Icon name="settings" size={14} /> Notification settings</button>}
      />
      <div className="flex items-center gap-3 mb-5 flex-wrap">
        <div className="relative w-[280px]">
          <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search messages, recipients..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" />
        </div>
        <div className="flex-1" />
        {['All', 'Email', 'WhatsApp', 'SMS'].map(f => (
          <button key={f} onClick={() => setCh(f)}
            className={`px-4 h-8 rounded-full text-sm transition-colors ${ch === f ? 'bg-neutral-900 text-white font-semibold' : 'bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50'}`}>
            {f}
          </button>
        ))}
      </div>
      <div className="bg-white border border-neutral-200 rounded-2xl overflow-x-auto">
        <table className="w-full text-sm min-w-[820px]">
          <thead>
            <tr className="border-b border-neutral-100 text-neutral-500">
              <th className="text-left px-5 py-3 font-medium">Channel</th>
              <th className="text-left px-5 py-3 font-medium">Subject</th>
              <th className="text-left px-5 py-3 font-medium">Recipient</th>
              <th className="text-left px-5 py-3 font-medium">Date</th>
              <th className="text-left px-5 py-3 font-medium">Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr><td colSpan={5} className="px-5 py-12 text-center text-sm text-neutral-500">No matches.</td></tr>
            ) : filtered.map(l => (
              <tr key={l.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="px-5 py-3"><Badge tone={tone[l.ch]}>{l.ch}</Badge></td>
                <td className="px-5 py-3 font-medium">{l.sub}</td>
                <td className="px-5 py-3 text-neutral-600">{l.to}</td>
                <td className="px-5 py-3 text-neutral-600">{l.date}</td>
                <td className="px-5 py-3"><Badge tone={l.status === 'Delivered' ? 'success' : 'error'}>{l.status}</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </DashShell>
  );
}

/* ===== Analytics Dashboard ===== */
function AnalyticsDashPage() {
  return (
    <DashShell active="/app/hub/analytics">
      <DashHeader title="Analytics Dashboard" subtitle="Performance across your listings, programmes and bookings."
        action={
          <div className="flex items-center gap-2">
            <select className="h-10 text-sm border border-neutral-300 rounded-lg px-3 bg-white">
              <option>Last 30 days</option><option>Last 90 days</option><option>This year</option>
            </select>
            <button className="h-10 px-4 border border-neutral-300 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50"><Icon name="download" size={14} /> Export</button>
          </div>
        }
      />
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <Metric label="Revenue" value="RM 24,860" delta="+18%" trend="up" />
        <Metric label="Bookings" value="34" delta="+6" trend="up" />
        <Metric label="Avg. order value" value="RM 731" delta="-3%" trend="down" />
        <Metric label="Repeat rate" value="42%" delta="+4%" trend="up" />
      </div>
      <div className="grid lg:grid-cols-3 gap-5 mb-5">
        <div className="lg:col-span-2 bg-white border border-neutral-200 rounded-2xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold">Revenue by week</h3>
            <div className="flex items-center gap-1">
              {['Revenue', 'Bookings', 'Visits'].map((t, i) => (
                <button key={t} className={`px-3 h-7 rounded-full text-xs ${i === 0 ? 'bg-neutral-900 text-white font-semibold' : 'text-neutral-600 hover:bg-neutral-100'}`}>{t}</button>
              ))}
            </div>
          </div>
          <BarChart />
        </div>
        <div className="bg-white border border-neutral-200 rounded-2xl p-5">
          <h3 className="font-semibold mb-4">Top listings</h3>
          <div className="space-y-3">
            {[
              { t: 'Batik Painting Workshop', p: 82 },
              { t: 'Sourdough Bread Class', p: 64 },
              { t: 'Pottery for Beginners', p: 48 },
              { t: 'Brand Identity Sprint', p: 26 },
            ].map(it => (
              <div key={it.t}>
                <div className="flex items-center justify-between text-sm mb-1">
                  <span className="truncate pr-2">{it.t}</span>
                  <span className="font-semibold num-tabular">{it.p}%</span>
                </div>
                <Progress value={it.p} tone="purple" />
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="grid lg:grid-cols-2 gap-5">
        <div className="bg-white border border-neutral-200 rounded-2xl p-5">
          <h3 className="font-semibold mb-4">Where bookings come from</h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {[{ src: 'Direct', n: '42%' }, { src: 'Search', n: '28%' }, { src: 'Programs', n: '18%' }, { src: 'Referral', n: '12%' }].map(s => (
              <div key={s.src} className="p-4 rounded-lg bg-neutral-50">
                <div className="text-xs text-neutral-500">{s.src}</div>
                <div className="text-2xl font-bold mt-1 num-tabular">{s.n}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="bg-white border border-neutral-200 rounded-2xl p-5">
          <h3 className="font-semibold mb-4">Reviews this month</h3>
          <div className="flex items-center gap-4">
            <div className="text-5xl font-bold num-tabular">4.9</div>
            <div className="flex-1 space-y-1">
              {[5, 4, 3, 2, 1].map(n => (
                <div key={n} className="flex items-center gap-2 text-xs">
                  <span className="w-4 text-neutral-500">{n}★</span>
                  <Progress value={n === 5 ? 80 : n === 4 ? 16 : n === 3 ? 4 : 0} tone="dark" className="flex-1" />
                  <span className="w-8 text-right num-tabular">{n === 5 ? 24 : n === 4 ? 5 : n === 3 ? 1 : 0}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </DashShell>
  );
}

/* ===== Manage Listings ===== */
const LISTINGS_BY_HUB = [
  { experiences: EXPERIENCES.slice(0, 6), expertise: EXPERTISE },
  {
    experiences: [
      { id: 'me1', title: 'AI Prompt Lab (Hands-on)', duration: '2 hours', location: 'Online', rating: 4.8 },
      { id: 'me2', title: 'Build Your First Chatbot', duration: '3 hours', location: 'Online', rating: 4.9 },
      { id: 'me3', title: 'Data Viz with AI', duration: '2.5 hours', location: 'Cyberjaya', rating: 4.7 },
      { id: 'me4', title: 'Automate Your Workflow with AI', duration: '2 hours', location: 'Online', rating: 4.8 },
    ],
    expertise: [
      { id: 'mx1', title: 'AI Strategy Workshop', delivery: 'Remote', category: 'Strategy', price: 'from RM 9,000' },
      { id: 'mx2', title: 'LLM Integration Sprint', delivery: 'Remote', category: 'Tech', price: 'from RM 18,000' },
      { id: 'mx3', title: 'Data Pipeline Setup', delivery: 'Remote', category: 'Tech', price: 'from RM 14,000' },
      { id: 'mx4', title: 'Prompt Ops Playbook', delivery: 'Online', category: 'Content', price: 'from RM 6,000' },
    ],
  },
  {
    experiences: [
      { id: 'sk1', title: 'Hand Lettering Basics', duration: '3 hours', location: 'Bangsar, KL', rating: 4.9 },
      { id: 'sk2', title: 'Brand Photography Walk', duration: '4 hours', location: 'Kuala Lumpur', rating: 4.8 },
      { id: 'sk3', title: 'Risograph Print Studio', duration: '5 hours', location: 'Petaling Jaya', rating: 5.0 },
    ],
    expertise: [
      { id: 'skx1', title: 'Brand Identity Sprint — 2 weeks', delivery: 'Online + 1 in-person', category: 'Branding', price: 'from RM 8,500' },
      { id: 'skx2', title: 'Packaging Design System', delivery: 'Remote', category: 'Design', price: 'from RM 11,000' },
      { id: 'skx3', title: 'Art Direction Retainer', delivery: 'Remote', category: 'Content', price: 'from RM 5,500' },
    ],
  },
];

function SvcThumb({ hue = 265 }) {
  return <span className="w-9 h-9 rounded-lg flex-shrink-0 inline-block overflow-hidden" style={{ background: `linear-gradient(135deg, oklch(0.9 0.05 ${hue}), oklch(0.82 0.09 ${hue + 20}))` }}><img src={scenePhoto(hue, 72, 72)} alt="" loading="lazy" onError={e => { e.currentTarget.style.display = 'none'; }} className="w-full h-full object-cover" /></span>;
}
function SvcRating({ v }) {
  return <span className="inline-flex items-center gap-1 font-semibold text-neutral-800">{Number(v).toFixed(1)} <Icon name="star" size={13} fill="#FBBF24" strokeWidth={0} className="text-amber-400" /></span>;
}
function SvcActions({ row = {}, kind = 'Experience' }) {
  const q = new URLSearchParams({ edit: String(row.id || ''), name: row.name || '', kind, desc: row.desc || '' }).toString();
  const editTo = `/app/service/create/basics?${q}`;
  const viewTo = row.slug ? (kind === 'Expertise' ? `/web/expertise/${row.slug}` : `/web/experiences/${row.slug}`) : null;
  return (
    <div className="flex items-center justify-end gap-2">
      <Link to={editTo}><button className="inline-flex items-center gap-1.5 h-8 px-3 border border-neutral-300 rounded-lg text-[13px] font-semibold hover:bg-neutral-50"><Icon name="edit" size={13} /> Edit</button></Link>
      {viewTo
        ? <Link to={viewTo} title="View live listing"><button className="w-8 h-8 rounded-lg border border-neutral-300 flex items-center justify-center text-neutral-500 hover:bg-neutral-50"><Icon name="eye" size={15} /></button></Link>
        : <button title="Preview" className="w-8 h-8 rounded-lg border border-neutral-300 flex items-center justify-center text-neutral-300 cursor-not-allowed"><Icon name="eye" size={15} /></button>}
      <RowKebab items={[
        { icon: 'copy', label: 'Duplicate' },
        { icon: 'document', label: row.status === 'Live' ? 'Set as draft' : 'Publish' },
        { icon: 'trash', label: 'Delete', danger: true },
      ]} />
    </div>
  );
}

/* Figma: pill dropdown filter with checkbox-style menu (Service / Status / Advanced filter) */
function PillFilter({ label, value, options, onChange, align = 'left' }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)}
        className="inline-flex items-center gap-2 h-9 px-4 rounded-full border border-neutral-200 bg-white text-sm text-neutral-800 hover:border-neutral-300 transition-colors">
        {label && <span className="text-neutral-500">{label}:</span>}
        <span className="font-semibold">{value}</span>
        <Icon name="chevronDown" size={15} className={`text-neutral-500 transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>
      {open && (
        <div className={`absolute ${align === 'right' ? 'right-0' : 'left-0'} top-[calc(100%+6px)] z-30 min-w-[210px] bg-white border border-neutral-200 rounded-2xl py-2`} style={{ boxShadow: '0 16px 40px rgba(0,0,0,0.13)' }}>
          {options.map(o => (
            <button key={o} onClick={() => { onChange(o); setOpen(false); }}
              className="w-full flex items-center justify-between gap-4 px-5 py-2.5 text-left text-[15px] hover:bg-neutral-50 transition-colors">
              <span className={value === o ? 'font-semibold text-neutral-900' : 'text-neutral-700'}>{o}</span>
              {value === o
                ? <Icon name="check" size={18} strokeWidth={2.5} className="text-neutral-900" />
                : <span className="w-5 h-5 rounded-md border-2 border-neutral-200" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function ExportButton() {
  return (
    <button className="inline-flex items-center gap-2 h-10 px-4 rounded-lg border border-neutral-200 bg-white text-sm font-semibold text-neutral-800 hover:bg-neutral-50">
      <Icon name="arrowUpRight" size={15} className="text-neutral-500" /> Export
    </button>
  );
}

function RowKebab({ items, plain }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)} className={plain ? 'text-neutral-400 hover:text-neutral-700' : 'w-8 h-8 rounded-lg border border-neutral-300 flex items-center justify-center text-neutral-500 hover:bg-neutral-50'}><Icon name="more" size={plain ? 16 : 15} /></button>
      {open && (
        <div className="absolute right-0 top-[calc(100%+6px)] z-30 min-w-[190px] bg-white border border-neutral-200 rounded-xl py-1.5" style={{ boxShadow: '0 16px 40px rgba(0,0,0,0.14)' }}>
          {items.map((it, i) => (
            <button key={i} onClick={() => setOpen(false)}
              className={`w-full flex items-center gap-3 px-4 py-2 text-left text-sm hover:bg-neutral-50 ${it.danger ? 'text-red-600' : 'text-neutral-700'}`}>
              <Icon name={it.icon} size={15} className={it.danger ? 'text-red-500' : 'text-neutral-500'} /> {it.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ===== Manage Hub Services — data ===== */
const SVC_STATUSES = ['All', 'Active', 'Inactive', 'Under review', 'Drafted', 'Backlog'];
const SVC_STATUS_POOL = ['Active', 'Active', 'Open for enquiries', 'Active', 'Drafted', 'Drafted'];
const SVC_DATES = ['12 Jan 2026', '12 Jan 2026', '15 Feb 2026', '20 Mar 2026', '25 Apr 2026', '15 Jun 2026'];
const SVC_BK = [
  { booked: 30, total: true, sessions: 3 },
  { booked: 27, capacity: 40 },
  { booked: 18, capacity: 30 },
  { booked: 34, capacity: 40 },
  { booked: 18, capacity: 20 },
  { booked: 21, capacity: 25 },
];
const BOOKING_ATTENDEES = [
  { id: 'b1', name: 'John Doe', email: 'johndoe@gmail.com', contact: '+6011-122-1234', session: 'Jul 13, 2026', booked: '1 week ago', tickets: '1x', paid: 'FREE' },
  { id: 'b2', name: 'Jane Smith', email: 'janesmith@yahoo.com', contact: '+6012-234-2345', session: 'Jul 13, 2026', booked: '2 weeks ago', tickets: '2x', paid: 'FREE' },
  { id: 'b3', name: 'Michael Brown', email: 'michaelbrown@hotmail.com', contact: '+6013-345-3456', session: 'Jul 13, 2026', booked: '1 week ago', tickets: '1x', paid: 'FREE' },
  { id: 'b4', name: 'Emily Davis', email: 'emilydavis@gmail.com', contact: '+6014-456-4567', session: 'Jul 11, 2026', booked: '5 days ago', tickets: '1x', paid: 'FREE' },
  { id: 'b5', name: 'David Wilson', email: 'davidwilson@outlook.com', contact: '+6015-567-5678', session: 'Jul 11, 2026', booked: '1 day ago', tickets: '1x', paid: 'FREE' },
  { id: 'b6', name: 'Sarah Johnson', email: 'sarahjohnson@icloud.com', contact: '+6016-678-6789', session: 'Jul 11, 2026', booked: '3 days ago', tickets: '2x', paid: 'FREE' },
];

function svcStatusColor(s) { return s === 'Active' ? 'text-green-600' : s === 'Open for enquiries' ? 'text-blue-600' : s === 'Under review' ? 'text-amber-600' : 'text-neutral-500'; }

function ServiceRowActions({ pinned }) {
  return (
    <div className="flex items-center justify-end gap-2">
      <button title="Pin" className={`w-8 h-8 rounded-lg border flex items-center justify-center transition-colors ${pinned ? 'border-neutral-900 text-neutral-900 bg-neutral-50' : 'border-neutral-300 text-neutral-500 hover:bg-neutral-50'}`}><Icon name="pin" size={15} fill={pinned ? '#111827' : 'none'} strokeWidth={pinned ? 0 : 2} /></button>
      <RowKebab items={[
        { icon: 'settings', label: 'Manage listing' },
        { icon: 'edit', label: 'Edit' },
        { icon: 'copy', label: 'Duplicate' },
        { icon: 'eye', label: 'View page' },
        { icon: 'send', label: 'Share' },
        { icon: 'star', label: 'Feature' },
        { icon: 'external', label: 'Share review link' },
        { icon: 'document', label: 'Unlist' },
      ]} />
    </div>
  );
}
function CheckCell() { return <input type="checkbox" className="w-4 h-4 rounded border-neutral-300 align-middle" />; }
function SortTh({ children, sortable, dir, className }) {
  return <th className={'px-5 py-3.5 whitespace-nowrap ' + (className || '')}><span className="inline-flex items-center gap-1">{children}{sortable && <Icon name={dir === 'up' ? 'chevronUp' : 'chevronDown'} size={13} className="text-neutral-400" />}</span></th>;
}
function BookingsCell({ b, onDetails }) {
  return (
    <div className="whitespace-nowrap leading-tight">
      <div>{b.total ? <span className="text-blue-600 font-semibold">{b.booked} Total</span> : <span className="text-blue-600 font-semibold">{b.booked}/{b.capacity}</span>} <button onClick={onDetails} className="text-blue-600 font-medium hover:underline">Details</button></div>
      {b.sessions && <div className="text-[12px] text-blue-600 mt-0.5">{b.sessions} Sessions</div>}
    </div>
  );
}

/* ===== Booking Details modal (attendee list) ===== */
function BookingDetailsModal({ svc, onClose }) {
  const [session, setSession] = useState('All');
  const [q, setQ] = useState('');
  const list = BOOKING_ATTENDEES.filter(a => q === '' || (a.name + ' ' + a.email).toLowerCase().includes(q.toLowerCase()));
  const bk = svc.bk || { booked: 6, capacity: 20 };
  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-[1040px] my-8 p-7" style={{ boxShadow: '0 24px 64px rgba(0,0,0,0.25)' }}>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-neutral-900" style={{ fontFamily: _pp }}>Booking Details</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="border border-neutral-200 rounded-xl overflow-x-auto mb-6">
          <table className="w-full text-sm min-w-[820px]">
            <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">{svc.kind === 'Expertise' ? 'EXPERTISE / EXPERT' : 'EXPERIENCE'}</th><th className="px-5 py-3">CREATED ON</th><th className="px-5 py-3">LAST MODIFIED</th><th className="px-5 py-3">STATUS</th><th className="px-5 py-3">LOCATION</th><th className="px-5 py-3">BOOKINGS</th><th className="px-5 py-3">RATING</th>
            </tr></thead>
            <tbody><tr>
              <td className="px-5 py-4"><div className="font-bold text-[13px] uppercase text-neutral-900">{svc.name}</div><div className="text-xs text-neutral-500 mt-0.5">{svc.host}</div></td>
              <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{svc.created}</td>
              <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{svc.modified}</td>
              <td className="px-5 py-4"><span className={'font-semibold ' + svcStatusColor(svc.status)}>{svc.status}</span></td>
              <td className="px-5 py-4 text-neutral-700">{svc.location}</td>
              <td className="px-5 py-4"><span className="text-blue-600 font-semibold">{bk.total ? bk.booked + ' Total' : bk.booked + '/' + bk.capacity}</span> <span className="text-blue-600">Details</span>{bk.sessions ? <div className="text-[12px] text-blue-600">{bk.sessions} Sessions</div> : null}</td>
              <td className="px-5 py-4"><SvcRating v={svc.rating || 4.8} /></td>
            </tr></tbody>
          </table>
        </div>
        <div className="flex items-center gap-3 mb-4"><h3 className="text-lg font-bold text-neutral-900" style={{ fontFamily: _pp }}>Booking List</h3><span className="text-sm font-semibold text-neutral-400">(30/60 Total)</span></div>
        <div className="flex items-center justify-between gap-3 mb-4 flex-wrap">
          <PillFilter label="Session" value={session} options={['All', 'Session 1', 'Session 2', 'Session 3']} onChange={setSession} />
          <div className="flex items-center gap-2.5">
            <div className="relative w-[240px]"><Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" /><input value={q} onChange={e => setQ(e.target.value)} placeholder="Search for..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" /></div>
            <ExportButton />
          </div>
        </div>
        <div className="border border-neutral-200 rounded-xl overflow-x-auto">
          <table className="w-full text-sm min-w-[860px]">
            <thead><tr className="text-left text-[12px] font-bold tracking-wide text-neutral-500 bg-neutral-50 border-b border-neutral-200">
              <th className="pl-5 pr-2 py-3 w-10"><CheckCell /></th><th className="px-5 py-3">CONTACT INFO</th><th className="px-5 py-3">EMAIL</th><th className="px-5 py-3">CONTACT</th><SortTh sortable dir="down">SESSIONS TIME &amp; DATE</SortTh><SortTh sortable dir="down">TIME BOOKED</SortTh><SortTh sortable dir="down">TICKET(S)</SortTh><th className="px-5 py-3">PAID AMOUNT</th><th className="px-5 py-3">ACTION</th>
            </tr></thead>
            <tbody>
              {list.map(a => (
                <tr key={a.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                  <td className="pl-5 pr-2 py-4"><CheckCell /></td>
                  <td className="px-5 py-4 font-bold text-[13px] uppercase text-neutral-900">{a.name}</td>
                  <td className="px-5 py-4 text-neutral-500">{a.email}</td>
                  <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{a.contact}</td>
                  <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{a.session}</td>
                  <td className="px-5 py-4 text-neutral-500 whitespace-nowrap">{a.booked}</td>
                  <td className="px-5 py-4 text-neutral-700">{a.tickets}</td>
                  <td className="px-5 py-4 text-neutral-700">{a.paid}</td>
                  <td className="px-5 py-4"><button onClick={() => { onClose(); navigate('/app/hub/booking/' + a.id); }} className="h-9 px-4 border border-neutral-300 rounded-lg text-[13px] font-semibold hover:bg-neutral-50">Details</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="flex items-center justify-between mt-4 text-sm"><span className="text-neutral-500">Showing 1-6 of 6</span><div className="flex items-center gap-1">{[1, 2, 3].map(p => <button key={p} className={`w-9 h-9 rounded-full text-sm font-semibold ${p === 1 ? 'bg-neutral-900 text-white' : 'text-neutral-500 hover:bg-neutral-100'}`}>{p}</button>)}<span className="px-1 text-neutral-400">…</span><button className="w-9 h-9 rounded-full text-sm font-semibold text-neutral-500 hover:bg-neutral-100">26</button></div></div>
      </div>
    </div>
  );
}

function ManageListingsDashPage() {
  const hub = useHub();
  const L = LISTINGS_BY_HUB[hubIdx(hub)] || LISTINGS_BY_HUB[0];
  const hubName = (typeof HUB_NAMES !== 'undefined' && HUB_NAMES[hubIdx(hub)]) || 'Your Hub';
  const [service, setService] = useState('Experience');
  const [status, setStatus] = useState('All');
  const [search, setSearch] = useState('');
  const [bkModal, setBkModal] = useState(null);
  const isExp = service === 'Experience';
  const src = isExp ? L.experiences : L.expertise;
  const _slugify = (t) => String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');

  const rows = src.map((e, i) => ({
    id: e.id, name: e.title, host: e.host || hubName,
    slug: e.slug || _slugify(e.title), kind: isExp ? 'Experience' : 'Expertise',
    hubSlug: e.hubSlug || _slugify(e.host || hubName),
    status: SVC_STATUS_POOL[i % SVC_STATUS_POOL.length],
    created: SVC_DATES[i % SVC_DATES.length], modified: SVC_DATES[i % SVC_DATES.length],
    location: e.location || 'Online', mode: e.location === 'Online' || !e.location ? 'Online' : '-',
    bk: SVC_BK[i % SVC_BK.length], rating: e.rating, hue: e.hue != null ? e.hue : 200 + i * 24, pinned: i === 0,
  })).filter(r => (status === 'All' || r.status === status) && (search === '' || (r.name + ' ' + r.host).toLowerCase().includes(search.toLowerCase())));

  return (
    <DashShell active="/app/hub/services/experiences">
      <DashHeader title="Manage Hub Services" subtitle="Manage and monitor all your hub's experiences, expertise and other services."
        action={<Link to="/app/service/create/type"><button className="h-10 px-4 border border-neutral-300 bg-white text-neutral-900 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50"><Icon name="plus" size={14} /> Add service</button></Link>}
      />
      <div className="flex items-center justify-between gap-3 mb-5 flex-wrap">
        <PillFilter label="Service" value={service} options={['Experience', 'Expertise']} onChange={v => { setService(v); setStatus('All'); }} />
        <div className="flex items-center gap-2.5">
          <div className="relative w-[240px]"><Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" /><input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search for..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" /></div>
          <ExportButton />
        </div>
      </div>
      <div className="flex items-center gap-2.5 mb-5 flex-wrap">
        {SVC_STATUSES.map(sc => (<button key={sc} onClick={() => setStatus(sc)} className={`px-4 h-9 rounded-full text-[13px] font-medium border transition-colors ${status === sc ? 'bg-neutral-900 text-white border-neutral-900' : 'bg-white text-neutral-600 border-neutral-200 hover:bg-neutral-50'}`}>{sc}</button>))}
      </div>
      <div className="bg-white border border-neutral-200 rounded-2xl overflow-x-auto">
        <table className="w-full text-sm min-w-[1080px]">
          <thead>
            <tr className="text-left text-[12px] font-bold tracking-wide text-neutral-500 border-b border-neutral-200">
              <th className="pl-5 pr-2 py-3.5 w-10"><CheckCell /></th>
              <SortTh>{isExp ? 'EXPERIENCE' : 'EXPERTISE & EXPERT'}</SortTh>
              {!isExp && <SortTh>MODE</SortTh>}
              <SortTh sortable dir="down">CREATED ON</SortTh>
              <SortTh sortable dir="down">LAST MODIFIED</SortTh>
              <SortTh>STATUS</SortTh>
              {isExp && <SortTh>LOCATION</SortTh>}
              <SortTh>BOOKINGS</SortTh>
              <SortTh sortable dir="up">RATING</SortTh>
              <th className="px-5 py-3.5 text-right">ACTION</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && <tr><td colSpan={9} className="px-5 py-12 text-center text-neutral-500">No services match this filter.</td></tr>}
            {rows.map((r) => (
              <tr key={r.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="pl-5 pr-2 py-4"><CheckCell /></td>
                <td className="px-5 py-4"><div className="flex items-center gap-3"><Link to={(r.kind === 'Expertise' ? '/web/expertise/' : '/web/experiences/') + r.slug}><SvcThumb hue={r.hue} /></Link><div><Link to={(r.kind === 'Expertise' ? '/web/expertise/' : '/web/experiences/') + r.slug} className="font-bold text-[13px] uppercase text-neutral-900 hover:text-blue-600 hover:underline">{r.name}</Link><div className="text-xs text-neutral-500 mt-0.5"><Link to={'/web/hubs/' + r.hubSlug} className="hover:text-neutral-800 hover:underline">{r.host}</Link></div></div></div></td>
                {!isExp && <td className="px-5 py-4 text-neutral-700">{r.mode}</td>}
                <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{r.created}</td>
                <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{r.modified}</td>
                <td className="px-5 py-4"><span className={'text-[13px] font-semibold ' + svcStatusColor(r.status)}>{r.status}</span></td>
                {isExp && <td className="px-5 py-4 text-neutral-700 whitespace-nowrap">{r.location}</td>}
                <td className="px-5 py-4"><BookingsCell b={r.bk} onDetails={() => setBkModal(r)} /></td>
                <td className="px-5 py-4"><SvcRating v={r.rating} /></td>
                <td className="px-5 py-4"><ServiceRowActions pinned={r.pinned} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="flex items-center justify-between mt-4 text-sm">
        <span className="text-neutral-500">Showing 1-{rows.length} of {rows.length}</span>
        <div className="flex items-center gap-1">{[1, 2, 3].map(p => <button key={p} className={`w-9 h-9 rounded-full text-sm font-semibold ${p === 1 ? 'bg-neutral-900 text-white' : 'text-neutral-500 hover:bg-neutral-100'}`}>{p}</button>)}<span className="px-1 text-neutral-400">…</span><button className="w-9 h-9 rounded-full text-sm font-semibold text-neutral-500 hover:bg-neutral-100">26</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 ml-1"><Icon name="arrowRight" size={15} /></button></div>
      </div>
      {bkModal && <BookingDetailsModal svc={bkModal} onClose={() => setBkModal(null)} />}
    </DashShell>
  );
}

/* ===== Manage Hub Gigs ===== */
const GIG_ROWS_BY_HUB = [
  [
    { id: 'g1', name: 'AI Prompt Engineering Coach', by: 'Service host', type: 'Coach', posted: 'Jun 9, 2026', proposals: 5, hire: '3 hires', status: 'Open' },
    { id: 'g2', name: 'Business Strategy Workshop', by: 'Created by Sara Lee', type: 'Trainer', posted: 'May 13, 2026', proposals: 1, hire: 'Ravi Kumar Sharma', status: 'Open' },
    { id: 'g3', name: 'MTA Personal Career Coaching', by: 'Created by Marlisa Ishak', type: 'Coach', posted: 'May 11, 2026', proposals: 2, hire: '-', status: 'Open' },
    { id: 'g4', name: 'Leadership Retreat', by: 'Created by Joseph Domingo', type: 'Coach', posted: 'Jan 22, 2026', proposals: 2, hire: '-', status: 'Open' },
    { id: 'g5', name: 'Digital Marketing Seminar', by: 'Created by Li Anne', type: 'Trainer', posted: 'Mar 9, 2026', proposals: 2, hire: 'Ahmad Rizal Hassan', status: 'Closed' },
  ],
  [
    { id: 'mg1', name: 'AI Curriculum Designer', by: 'Created by Faiz F.', type: 'Trainer', posted: 'Jun 14, 2026', proposals: 4, hire: 'Nadia Rahman', status: 'Open' },
    { id: 'mg2', name: 'LLM Integration Engineer', by: 'Created by Amir T.', type: 'Coach', posted: 'Jun 2, 2026', proposals: 7, hire: '2 hires', status: 'Open' },
    { id: 'mg3', name: 'Data Storytelling Workshop', by: 'Created by Sofia P.', type: 'Trainer', posted: 'May 20, 2026', proposals: 3, hire: '-', status: 'Open' },
    { id: 'mg4', name: 'Prompt Ops Consultant', by: 'Created by Marcus O.', type: 'Coach', posted: 'Apr 8, 2026', proposals: 1, hire: 'Rafael Tan', status: 'Closed' },
  ],
  [
    { id: 'sg1', name: 'Brand Identity Facilitator', by: 'Created by Studio Kuala', type: 'Coach', posted: 'Jun 11, 2026', proposals: 6, hire: '4 hires', status: 'Open' },
    { id: 'sg2', name: 'Risograph Print Instructor', by: 'Created by Dina L.', type: 'Trainer', posted: 'May 30, 2026', proposals: 2, hire: 'Tasha Lim', status: 'Open' },
    { id: 'sg3', name: 'Photography Mentor', by: 'Created by Frame & Field', type: 'Coach', posted: 'Mar 18, 2026', proposals: 3, hire: '-', status: 'Closed' },
  ],
];
function gigHue(s) { let h = 0; for (let i = 0; i < String(s).length; i++) h = (h + String(s).charCodeAt(i) * 7) % 360; return h; }

function ManageGigsDashPage() {
  const hub = useHub();
  const GIG_ROWS = GIG_ROWS_BY_HUB[hubIdx(hub)] || GIG_ROWS_BY_HUB[0];
  const [status, setStatus] = useState('All');
  const [search, setSearch] = useState('');
  const q = search.toLowerCase();
  const rows = GIG_ROWS.filter(g => (status === 'All' || g.status === status) && (q === '' || (g.name + ' ' + g.by).toLowerCase().includes(q)));
  return (
    <DashShell active="/app/hub/gigs">
      <DashHeader title="Manage Hub Gigs" subtitle="Manage and monitor all your hub's gigs."
        action={<Link to="/app/onboarding/job/details"><button className="h-10 px-4 border border-neutral-300 bg-white text-neutral-900 rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-50"><Icon name="plus" size={14} /> Add job post</button></Link>}
      />
      <div className="flex items-center justify-between gap-3 mb-5 flex-wrap">
        <div className="flex items-center gap-2.5">
          {['All', 'Open', 'Closed'].map(t => (<button key={t} onClick={() => setStatus(t)} className={`px-4 h-9 rounded-full text-[13px] font-medium border transition-colors ${status === t ? 'bg-neutral-900 text-white border-neutral-900' : 'bg-white text-neutral-600 border-neutral-200 hover:bg-neutral-50'}`}>{t}</button>))}
        </div>
        <div className="flex items-center gap-2.5">
          <div className="relative w-[240px]"><Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" /><input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search for..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" /></div>
          <ExportButton />
        </div>
      </div>
      <div className="bg-white border border-neutral-200 rounded-2xl overflow-x-auto">
        <table className="w-full text-sm min-w-[980px]">
          <thead>
            <tr className="text-left text-[12px] font-bold tracking-wide text-neutral-500 border-b border-neutral-200">
              <th className="pl-5 pr-2 py-3.5 w-10"><CheckCell /></th>
              <SortTh>GIG DETAILS</SortTh>
              <SortTh sortable dir="down">TYPE</SortTh>
              <SortTh sortable dir="down">POSTED ON</SortTh>
              <SortTh sortable dir="down">PROPOSALS</SortTh>
              <SortTh>HIRE</SortTh>
              <SortTh sortable dir="down">STATUS</SortTh>
              <th className="px-5 py-3.5">ACTION</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && <tr><td colSpan={8} className="px-5 py-12 text-center text-neutral-500">No gigs match this filter.</td></tr>}
            {rows.map((g) => (
              <tr key={g.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
                <td className="pl-5 pr-2 py-4"><CheckCell /></td>
                <td className="px-5 py-4"><div className="flex items-center gap-3"><SvcThumb hue={gigHue(g.name)} /><div><div className="font-bold text-[13px] uppercase text-neutral-900">{g.name}</div><div className="text-xs text-neutral-500 mt-0.5">{g.by}</div></div></div></td>
                <td className="px-5 py-4 text-neutral-700">{g.type}</td>
                <td className="px-5 py-4 text-neutral-600 whitespace-nowrap">{g.posted}</td>
                <td className="px-5 py-4 text-neutral-700 num-tabular">{g.proposals}</td>
                <td className="px-5 py-4 whitespace-nowrap">{g.hire === '-' ? <span className="text-neutral-400">-</span> : <Link to="/app/hub/jobs/posts" className="text-blue-600 font-medium hover:underline">{g.hire}</Link>}</td>
                <td className="px-5 py-4"><span className={`text-[13px] font-semibold ${g.status === 'Open' ? 'text-green-600' : 'text-neutral-500'}`}>{g.status}</span></td>
                <td className="px-5 py-4"><div className="flex items-center gap-2"><Link to="/app/hub/jobs/posts"><button className="inline-flex items-center gap-2 h-9 px-3.5 border border-neutral-300 rounded-lg text-[13px] font-semibold hover:bg-neutral-50"><Icon name="eye" size={14} /> Details</button></Link><RowKebab items={[{ icon: 'edit', label: 'Edit post' }, { icon: 'copy', label: 'Duplicate' }, { icon: 'send', label: 'Share' }, { icon: 'trash', label: 'Close gig', danger: true }]} /></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="flex items-center justify-between mt-4 text-sm">
        <span className="text-neutral-500">Showing 1-{rows.length} of {rows.length}</span>
        <div className="flex items-center gap-1">{[1, 2, 3].map(p => <button key={p} className={`w-9 h-9 rounded-full text-sm font-semibold ${p === 1 ? 'bg-neutral-900 text-white' : 'text-neutral-500 hover:bg-neutral-100'}`}>{p}</button>)}<span className="px-1 text-neutral-400">…</span><button className="w-9 h-9 rounded-full text-sm font-semibold text-neutral-500 hover:bg-neutral-100">26</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 ml-1"><Icon name="arrowRight" size={15} /></button></div>
      </div>
    </DashShell>
  );
}


function ManageProgramsDashPage() {
  const [tab, setTab] = useState('All');
  const [search, setSearch] = useState('');
  const programs = [
    { id: 'pg1', title: 'AI4U Program', status: 'Published', learners: 1751, exp: 215, start: '06 May 2026', hue: 290 },
    { id: 'pg2', title: 'AI Fluency by Microsoft', status: 'Published', learners: 642, exp: 28, start: '12 Jul 2025', hue: 220 },
    { id: 'pg3', title: 'Mereka Career Accelerator', status: 'Draft', learners: 0, exp: 0, start: '—', hue: 340 },
    { id: 'pg4', title: 'Sustainability for SMEs', status: 'Scheduled', learners: 0, exp: 12, start: '01 Aug 2026', hue: 170 },
  ];
  const tone = { Published: 'success', Draft: 'neutral', Scheduled: 'warning' };
  const filtered = programs.filter(p => (tab === 'All' || p.status === tab) && (search === '' || p.title.toLowerCase().includes(search.toLowerCase())));
  return (
    <DashShell active="/app/program/admin/feed">
      <DashHeader title="Manage Programs" subtitle="Cohorts, courses and curated journeys you run."
        action={
          <Link to="/app/program/create/basic">
            <button className="h-10 px-4 bg-neutral-900 text-white rounded-lg text-sm font-semibold inline-flex items-center gap-2 hover:bg-neutral-800"><Icon name="plus" size={14} /> Create program</button>
          </Link>
        }
      />
      <div className="flex items-center gap-3 mb-5 flex-wrap">
        <div className="relative w-[280px]">
          <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search programs..." className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" />
        </div>
        <div className="flex-1" />
        {['All', 'Published', 'Scheduled', 'Draft'].map(f => (
          <button key={f} onClick={() => setTab(f)}
            className={`px-4 h-8 rounded-full text-sm transition-colors ${tab === f ? 'bg-neutral-900 text-white font-semibold' : 'bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50'}`}>
            {f}
          </button>
        ))}
      </div>
      <div className="grid sm:grid-cols-2 xl:grid-cols-3 gap-5">
        {filtered.length === 0 ? (
          <EmptyState message="No programs match this filter." className="sm:col-span-2 xl:col-span-3" />
        ) : filtered.map(p => (
          <div key={p.id} className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <div className="aspect-[16/9] relative" style={{ background: `linear-gradient(135deg, oklch(0.82 0.12 ${p.hue}), oklch(0.65 0.18 ${p.hue + 30}))` }}>
              <Badge tone={tone[p.status]} className="absolute top-3 left-3">{p.status}</Badge>
            </div>
            <div className="p-5">
              <h3 className="font-bold">{p.title}</h3>
              <p className="text-xs text-neutral-500 mt-1">Starts {p.start}</p>
              <div className="mt-4 pt-4 border-t border-neutral-100 grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
                <div><div className="text-neutral-500">Learners</div><div className="font-bold num-tabular">{p.learners.toLocaleString()}</div></div>
                <div><div className="text-neutral-500">Experts</div><div className="font-bold num-tabular">{p.exp}</div></div>
              </div>
              <div className="mt-4 flex gap-2">
                <Link to="/app/program/admin/feed" className="flex-1"><button className="w-full h-9 border border-neutral-300 rounded-full text-xs font-semibold hover:bg-neutral-50">Open</button></Link>
                <button className="w-9 h-9 border border-neutral-300 rounded-full text-neutral-500 hover:bg-neutral-50 inline-flex items-center justify-center"><Icon name="more" size={14} /></button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </DashShell>
  );
}
