/* Mereka v2 — app shells (public web, user dashboard, hub dashboard) */

/* ============ Public web header & footer ============ */
const UPSKILL_LINKS = [
  { label: 'Courses', to: '/app/dashboard/courses', icon: 'play', desc: 'Single, self-paced lessons on one topic' },
  { label: 'Program', to: '/web/learning-paths', icon: 'layers', desc: 'Curated learning paths with a certificate' },
  { label: 'Experience', to: '/web/experiences', icon: 'compass', desc: 'Hands-on workshops, trips & live sessions' },
];
const PRIMARY_NAV = [
  { label: 'Find experts', to: '/web/experts', dropdown: true },
  { label: 'Find gigs', to: '/web/jobs', dropdown: true },
  { label: 'Upskill', to: '/web/experiences', dropdown: true, menu: UPSKILL_LINKS },
  { label: 'Workspace', to: '/web/hubs' },
  { label: 'Why Mereka', to: '/web/programs' },
];

function WebHeader({ active, showDashboardCTA = true }) {
  const [open, setOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [navMenu, setNavMenu] = useState(null);
  const userMenuRef = useRef(null);
  const navRef = useRef(null);
  const path = _currentPath();
  const onAppPage = path.startsWith('/app/') && !path.startsWith('/app/login');

  useEffect(() => {
    if (!userMenuOpen) return;
    const handler = (e) => {
      if (userMenuRef.current && !userMenuRef.current.contains(e.target)) {
        setUserMenuOpen(false);
      }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, [userMenuOpen]);

  useEffect(() => {
    if (!navMenu) return;
    const handler = (e) => {
      if (navRef.current && !navRef.current.contains(e.target)) setNavMenu(null);
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, [navMenu]);

  return (
    <header className="sticky top-0 z-40 bg-white border-b border-neutral-100">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-4 lg:px-6">
        <div className="flex items-center gap-6 h-[68px]">
          <Link to="/web" className="flex-shrink-0" aria-label="Mereka home">
            <div style={{ height: 32 }}><MerekaLogo /></div>
          </Link>

          <nav ref={navRef} className="hidden lg:flex items-center gap-1 ml-2">
            {PRIMARY_NAV.map(item => {
              const isActive = active === item.to;
              if (item.menu) {
                const isOpen = navMenu === item.label;
                return (
                  <div key={item.label} className="relative">
                    <button onClick={() => setNavMenu(o => o === item.label ? null : item.label)}
                      className={`inline-flex items-center gap-1 px-3 py-2 text-[15px] font-medium rounded-lg transition-colors ${isActive || isOpen ? 'text-neutral-900 bg-neutral-100' : 'text-neutral-700 hover:text-neutral-900'}`}>
                      {item.label}
                      <Icon name="chevronDown" size={14} className={`text-neutral-500 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
                    </button>
                    {isOpen && (
                      <div className="absolute left-0 top-[calc(100%+8px)] w-[330px] bg-white rounded-2xl border border-neutral-100 p-2 z-50"
                           style={{ boxShadow: '0 16px 40px rgba(0,0,0,0.14)' }}>
                        {item.menu.map(m => (
                          <Link key={m.label} to={m.to} onClick={() => setNavMenu(null)}
                            className="flex items-start gap-3 p-3 rounded-xl hover:bg-neutral-50 transition-colors group">
                            <span className="flex-shrink-0 w-9 h-9 rounded-lg bg-neutral-100 text-neutral-900 flex items-center justify-center group-hover:bg-neutral-900 group-hover:text-white transition-colors">
                              <Icon name={m.icon} size={16} />
                            </span>
                            <span className="min-w-0">
                              <span className="block text-sm font-semibold text-neutral-900">{m.label}</span>
                              <span className="block text-xs text-neutral-500 leading-snug">{m.desc}</span>
                            </span>
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                );
              }
              return (
                <Link key={item.label} to={item.to}
                  className={`inline-flex items-center gap-1 px-3 py-2 text-[15px] font-medium rounded-lg transition-colors ${isActive ? 'text-neutral-900' : 'text-neutral-700 hover:text-neutral-900'}`}>
                  {item.label}
                  {item.dropdown && <Icon name="chevronDown" size={14} className="text-neutral-500" />}
                </Link>
              );
            })}
          </nav>

          <div className="flex-1" />

          <div className="hidden md:block w-[280px]">
            <SearchInput placeholder="What are you looking for?" size="sm" className="w-full" />
          </div>

          {showDashboardCTA && (
            onAppPage ? (
              <Link to="/web" className="hidden lg:inline-flex items-center gap-2 px-4 h-10 text-sm font-semibold text-white bg-neutral-900 hover:bg-neutral-800 rounded-full transition-colors">
                Switch to User
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M21 12a9 9 0 0 1-15 6.7L3 16" />
                  <path d="M3 12a9 9 0 0 1 15-6.7L21 8" />
                  <polyline points="21 3 21 8 16 8" />
                  <polyline points="3 21 3 16 8 16" />
                </svg>
              </Link>
            ) : (
              <Link to="/app/dashboard/overview" className="hidden lg:inline-flex items-center gap-1 px-4 h-10 text-sm font-semibold text-white bg-[#FF1B6B] hover:bg-[#e0185f] rounded-full transition-colors">
                My Dashboard
              </Link>
            )
          )}

          <div className="hidden lg:flex items-center gap-3">
            <Link to="/app/dashboard/notifications" className="relative p-1.5 hover:bg-neutral-100 rounded-lg">
              <Icon name="bell" size={20} className="text-neutral-700" />
              <span className="absolute top-1 right-1 w-2 h-2 bg-blue-500 rounded-full" />
            </Link>
            <Link to="/app/dashboard/chats" className="relative p-1.5 hover:bg-neutral-100 rounded-lg">
              <Icon name="message" size={20} className="text-neutral-700" />
              <span className="absolute top-1 right-1 w-2 h-2 bg-blue-500 rounded-full" />
            </Link>
            <div className="relative" ref={userMenuRef}>
              <button onClick={() => setUserMenuOpen(o => !o)} className="ml-1 rounded-full hover:ring-2 hover:ring-neutral-200 transition" aria-label="Account">
                <Avatar name="Faiz Fadhillah" size={36} />
              </button>
              {userMenuOpen && <ProfileDropdown onClose={() => setUserMenuOpen(false)} />}
            </div>
          </div>

          <button onClick={() => setOpen(!open)} className="lg:hidden p-2"><Icon name={open ? 'close' : 'menu'} size={22} /></button>
        </div>

        {open && (
          <div className="lg:hidden py-3 space-y-1 border-t border-neutral-100">
            {PRIMARY_NAV.map(item => (
              <div key={item.label}>
                <Link to={item.to} className="block px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-neutral-50 rounded-lg">
                  {item.label}
                </Link>
                {item.menu && (
                  <div className="pl-4 space-y-0.5 pb-1">
                    {item.menu.map(m => (
                      <Link key={m.label} to={m.to} className="flex items-center gap-2 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-50 rounded-lg">
                        <Icon name={m.icon} size={14} className="text-neutral-400" />
                        {m.label}
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            ))}
            <Link to={onAppPage ? '/web' : '/app/dashboard/overview'} className="block px-3 py-2 text-sm font-medium text-white bg-neutral-900 rounded-lg text-center">
              {onAppPage ? 'Switch to User' : 'Open Dashboard'}
            </Link>
          </div>
        )}
      </div>
    </header>
  );
}

function ProfileDropdown({ onClose }) {
  const items = [
    { label: 'My Expert Profile', to: '/app/dashboard/overview' },
    { label: 'Business Profile', to: '/app/hub/settings/account' },
    { label: 'Settings', to: '/app/hub/settings' },
    { label: 'Resources', to: '/web/programs' },
    { label: 'Help Center', to: '/web' },
  ];
  return (
    <div className="absolute right-0 top-12 w-[320px] bg-white border border-neutral-200 rounded-2xl shadow-2xl py-3 z-50">
      <div className="px-5 py-3 border-b border-neutral-100">
        <p className="text-xs font-bold text-neutral-700 tracking-wider uppercase inline-flex items-center gap-2">
          Signed in as
          <span className="inline-flex items-center gap-1.5 bg-neutral-900 text-white px-2 py-0.5 rounded">
            <span style={{ width: 14, height: 14 }}><img src="/mereka-logo-white.svg" alt="" style={{ width: 14, height: 14 }} /></span>
            FAIZ
          </span>
        </p>
      </div>
      <div className="py-2">
        {items.map(it => (
          <Link key={it.label} to={it.to} onClick={onClose}
            className="block px-5 py-2.5 text-base font-bold text-neutral-900 hover:bg-neutral-50">
            {it.label}
          </Link>
        ))}
        <div className="border-t border-neutral-100 my-2" />
        <Link to="/app/login" onClick={onClose}
          className="block px-5 py-2.5 text-base font-bold text-red-600 hover:bg-red-50">
          Log Out
        </Link>
      </div>
    </div>
  );
}

function WebFooter() {
  const cols = [
    { title: 'Explore', items: ['Experiences', 'Experts', 'Expertise', 'Jobs', 'Hubs', 'Programs'] },
    { title: 'Hubs', items: ['List your hub', 'Hub guidelines', 'Subscription plans', 'Hub directory'] },
    { title: 'Experts', items: ['Become an Expert', 'Apply to jobs', 'Verification', 'Payouts'] },
    { title: 'Company', items: ['About Mereka', 'Press', 'Careers', 'Contact'] },
    { title: 'Support', items: ['Help center', 'Trust & safety', 'Privacy policy', 'Terms of service'] },
  ];
  return (
    <footer className="bg-neutral-900 text-neutral-300">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-4 lg:px-8 pt-16 pb-10">
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-8">
          <div className="col-span-2 md:col-span-3 lg:col-span-1">
            <div style={{ height: 40 }}><MerekaLogo dark /></div>
            <p className="mt-4 text-sm text-neutral-400 leading-relaxed">
              The future of work, made for the creative & digital economy.
            </p>
          </div>
          {cols.map(c => (
            <div key={c.title}>
              <h4 className="text-sm font-semibold text-white mb-3">{c.title}</h4>
              <ul className="space-y-2 text-sm text-neutral-400">
                {c.items.map(i => <li key={i}><a href="#" className="hover:text-white">{i}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div className="mt-12 pt-6 border-t border-neutral-800 flex items-center justify-between text-xs text-neutral-500">
          <span>© 2026 Mereka. All rights reserved.</span>
          <div className="flex items-center gap-4">
            <a href="#" className="hover:text-white">English</a>
            <a href="#" className="hover:text-white">Bahasa Malaysia</a>
            <a href="#" className="hover:text-white">中文</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function PublicShell({ children, route }) {
  return (
    <div className="min-h-screen flex flex-col">
      <HomeHeader />
      <main className="flex-1">{children}</main>
      <WebFooter />
    </div>
  );
}

/* ============ Dashboard navbar (shared by user & hub) ============ */
function DashboardNavbar({ context = 'user', hubName = 'Kraf KL Studio' }) {
  return (
    <header className="bg-white border-b border-neutral-200">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-6">
        <div className="flex items-center justify-between h-[68px]">
          <div className="flex items-center gap-6">
            <Link to="/web" className="flex-shrink-0" aria-label="Mereka home">
              <div style={{ height: 36 }}><MerekaLogo /></div>
            </Link>
            <div className="hidden lg:flex items-center gap-1 text-sm">
              <Link to="/app/dashboard/overview" className={`px-3 py-2 rounded-lg font-medium ${context === 'user' ? 'text-neutral-900 bg-neutral-100' : 'text-neutral-600 hover:bg-neutral-50'}`}>
                Personal
              </Link>
              <Link to="/app/hub/calendar" className={`px-3 py-2 rounded-lg font-medium flex items-center gap-2 ${context === 'hub' ? 'text-neutral-900 bg-neutral-100' : 'text-neutral-600 hover:bg-neutral-50'}`}>
                <span>{context === 'hub' ? hubName : 'Business'}</span>
                <Icon name="chevronDown" size={14} />
              </Link>
            </div>
          </div>

          <div className="hidden md:block flex-1 max-w-xs mx-8">
            <SearchInput placeholder="Search…" size="sm" />
          </div>

          <div className="flex items-center gap-2">
            <Link to={context === 'hub' ? '/app/hub/notifications' : '/app/dashboard/notifications'} className="relative p-2 rounded-lg hover:bg-neutral-100">
              <Icon name="bell" size={18} />
              <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full" />
            </Link>
            <Link to={context === 'hub' ? '/app/hub/chats' : '/app/dashboard/chats'} className="relative p-2 rounded-lg hover:bg-neutral-100">
              <Icon name="chat" size={18} />
            </Link>
            <button className="p-1 rounded-full hover:bg-neutral-100" aria-label="Account">
              <Avatar name="Faiz Fadhillah" size={36} />
            </button>
          </div>
        </div>
      </div>
    </header>
  );
}

/* ============ User dashboard side menu ============ */
function UserDashboardMenu({ active }) {
  return (
    <aside className="w-full lg:w-[280px] flex-shrink-0 bg-[#eeeeee] lg:bg-transparent">
      <div className="p-6 lg:sticky lg:top-[84px]">
        <div className="flex items-center gap-3 mb-6">
          <Avatar name="Faiz Fadhillah" size={56} />
          <div>
            <div className="text-xs text-neutral-500">Welcome back</div>
            <h3 className="text-base font-semibold text-neutral-900">Faiz Fadhillah</h3>
            <Link to="/app/dashboard/overview" className="text-xs text-primary hover:underline">View profile →</Link>
          </div>
        </div>

        <nav className="space-y-0.5">
          {USER_NAV.map(item => {
            const isActive = active === item.to;
            return (
              <Link key={item.to} to={item.to}
                className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-colors ${isActive ? 'bg-white text-neutral-900 font-semibold shadow-sm' : 'text-neutral-700 hover:bg-white/60'}`}>
                <Icon name={item.icon} size={16} className={isActive ? 'text-neutral-900' : 'text-neutral-500'} />
                <span>{item.label}</span>
              </Link>
            );
          })}
        </nav>

        <div className="mt-6 p-4 rounded-xl bg-white border border-neutral-200">
          <p className="text-xs font-semibold text-neutral-900 mb-1">Become an Expert</p>
          <p className="text-xs text-neutral-500 mb-3">List your skills and start earning.</p>
          <Link to="/app/onboarding/expert/welcome" className="inline-flex items-center gap-1 text-xs font-semibold text-primary">
            Get started <Icon name="arrowRight" size={12} />
          </Link>
        </div>
      </div>
    </aside>
  );
}

function UserShell({ children, route, title }) {
  // Unified app chrome: same top navbar (HomeHeader) + side nav (DashSideNav)
  // used by "My Dashboard" and the rest of the authenticated app.
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="flex max-w-[min(2560px,95vw)] mx-auto">
        <DashSideNav active={route} />
        <main className="flex-1 min-w-0 py-6 pr-6">
          {title && <h1 className="text-2xl lg:text-[28px] font-bold text-neutral-900 mb-6">{title}</h1>}
          {children}
        </main>
      </div>
    </div>
  );
}

/* ============ Hub dashboard chrome ============ */
function HubNavbar({ active }) {
  // Top tab bar within hub (Overview / Calendar / Bookings / etc)
  return (
    <div className="bg-white border-b border-neutral-200">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-6">
        <div className="flex items-center gap-1 -mb-px overflow-x-auto scrollbar-thin">
          {HUB_NAV.map(item => {
            const isActive = active === item.to || (active || '').startsWith(item.to);
            return (
              <Link key={item.to} to={item.to}
                className={`flex items-center gap-2 px-4 py-3 text-sm whitespace-nowrap border-b-2 transition-colors ${isActive ? 'border-neutral-900 text-neutral-900 font-semibold' : 'border-transparent text-neutral-600 hover:text-neutral-900'}`}>
                <Icon name={item.icon} size={15} />
                {item.label}
              </Link>
            );
          })}
          <div className="flex-1" />
          <Link to="/app/hub/services/experiences" className={`px-4 py-3 text-sm whitespace-nowrap border-b-2 ${(active || '').includes('/services/') ? 'border-neutral-900 text-neutral-900 font-semibold' : 'border-transparent text-neutral-600 hover:text-neutral-900'}`}>Services</Link>
          <Link to="/app/hub/jobs/posts" className={`px-4 py-3 text-sm whitespace-nowrap border-b-2 ${(active || '').includes('/jobs/') ? 'border-neutral-900 text-neutral-900 font-semibold' : 'border-transparent text-neutral-600 hover:text-neutral-900'}`}>Jobs</Link>
            <Link to="/app/hub/settings/account" className={`px-4 py-3 text-sm whitespace-nowrap border-b-2 ${(active || '').includes('/settings/') ? 'border-neutral-900 text-neutral-900 font-semibold' : 'border-transparent text-neutral-600 hover:text-neutral-900'}`}>Settings</Link>
        </div>
      </div>
    </div>
  );
}

function HubSidebar() {
  const [profileProgress] = useState(72);
  const today = new Date();
  const month = today.getMonth();
  const year = today.getFullYear();
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const days = [];
  const startOffset = firstDay === 0 ? 6 : firstDay - 1;
  for (let i = 0; i < startOffset; i++) days.push({ day: '', current: false });
  for (let d = 1; d <= daysInMonth; d++) days.push({ day: d, current: true, today: d === today.getDate() });
  while (days.length < 42) days.push({ day: '', current: false });

  return (
    <aside className="w-[300px] flex-shrink-0 hidden xl:block">
      <div className="sticky top-6 space-y-4">
        <Card>
          <div className="flex items-center gap-3 mb-4">
            <Avatar name="Kraf KL" size={56} />
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between mb-0.5">
                <span className="text-xs text-neutral-500">Business</span>
                <span className="text-[11px] font-bold text-white bg-neutral-900 px-2 py-0.5 rounded">PRO</span>
              </div>
              <h3 className="font-semibold text-neutral-900 truncate">Kraf KL Studio</h3>
            </div>
          </div>
          <Progress value={profileProgress} className="mb-2" />
          <div className="flex items-center justify-between text-xs">
            <a href="#" className="text-primary font-medium hover:underline">Complete profile</a>
            <span className="font-semibold num-tabular">{profileProgress}%</span>
          </div>
          <div className="mt-4 pt-4 border-t border-neutral-100 space-y-2 text-sm">
            <Row label="Overall rating"><Stars rating={4.9} size={12} /></Row>
            <Row label="Total reviews">128</Row>
            <Row label="Response rate">96%</Row>
          </div>
        </Card>

        <Card padding="p-4">
          <h4 className="text-sm font-semibold text-neutral-900 mb-3">My calendar</h4>
          <div className="grid grid-cols-7 gap-1 mb-1">
            {['M','T','W','T','F','S','S'].map((d, i) => (
              <div key={i} className="text-[11px] font-medium text-neutral-400 text-center py-1">{d}</div>
            ))}
          </div>
          <div className="grid grid-cols-7 gap-1">
            {days.map((d, i) => (
              <div key={i} className={`aspect-square flex items-center justify-center text-xs rounded-full ${
                !d.current ? 'text-neutral-300' :
                d.today ? 'bg-primary text-white font-semibold' : 'text-neutral-700 hover:bg-neutral-100'
              }`}>
                {d.day}
              </div>
            ))}
          </div>
        </Card>

        <Card padding="p-4">
          <h4 className="text-sm font-semibold text-neutral-900 mb-3">Quick actions</h4>
          <div className="space-y-2">
            {[
              { label: 'Add experience', icon: 'plus', to: '/app/onboarding/experience/select-type' },
              { label: 'List expertise', icon: 'award', to: '/app/onboarding/expertise/welcome' },
              { label: 'Post a job', icon: 'briefcase', to: '/app/onboarding/job/details' },
              { label: 'Invite team member', icon: 'send', to: '/app/hub/settings/members' },
            ].map(a => (
              <Link key={a.label} to={a.to}
                    className="flex items-center gap-3 px-3 py-2.5 border border-neutral-200 rounded-lg text-sm text-neutral-700 hover:bg-neutral-50">
                <Icon name={a.icon} size={14} className="text-neutral-500" />
                <span>{a.label}</span>
              </Link>
            ))}
          </div>
        </Card>
      </div>
    </aside>
  );
}

function Row({ label, children }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-neutral-500">{label}</span>
      <span className="font-medium text-neutral-900">{children}</span>
    </div>
  );
}

function HubShell({ children, route, title, breadcrumb, action, withSidebar = false }) {
  return (
    <div className="min-h-screen flex flex-col bg-neutral-50">
      <HomeHeader />
      <HubNavbar active={route} />
      <div className="max-w-[min(2560px,95vw)] mx-auto w-full px-6 py-8 flex-1 flex gap-6">
        {withSidebar && <HubSidebar />}
        <div className="flex-1 min-w-0">
          {breadcrumb && <div className="text-xs text-neutral-500 mb-2">{breadcrumb}</div>}
          {(title || action) && (
            <div className="flex items-start justify-between gap-4 mb-6">
              {title && <h1 className="text-2xl font-bold text-neutral-900">{title}</h1>}
              {action}
            </div>
          )}
          {children}
        </div>
      </div>
    </div>
  );
}

/* ============ Hub settings sub-shell ============ */
function HubSettingsShell({ active, title, children }) {
  return (
    <HubShell route="/app/hub/settings/account" title="Settings">
      <div className="flex gap-8">
        <aside className="hidden lg:block w-[220px] flex-shrink-0">
          <nav className="space-y-0.5">
            {HUB_NAV_SETTINGS.map(item => {
              const isActive = active === item.to;
              return (
                <Link key={item.to} to={item.to}
                  className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${isActive ? 'bg-neutral-900 text-white font-medium' : 'text-neutral-700 hover:bg-neutral-100'}`}>
                  <Icon name={item.icon} size={15} />
                  {item.label}
                </Link>
              );
            })}
          </nav>
        </aside>
        <div className="flex-1 min-w-0">
          <h2 className="text-xl font-semibold text-neutral-900 mb-6">{title}</h2>
          {children}
        </div>
      </div>
    </HubShell>
  );
}

Object.assign(window, {
  WebHeader, WebFooter, PublicShell,
  DashboardNavbar, UserDashboardMenu, UserShell,
  HubNavbar, HubSidebar, HubShell, HubSettingsShell,
});
