'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Icon, type IconName } from './icon';
import { useLang } from './i18n';

export type NavItem = { href: string; icon: IconName; label: string; count?: string; alert?: boolean };
export type NavGroup = { label?: string; items: NavItem[] };

export type ShellProps = {
  variant: 'agency' | 'admin';
  brandSub: string;
  envBadge?: string;
  workspace?: { initials: string; name: string; plan: string };
  nav: NavGroup[];
  sidebarFooter?: React.ReactNode;
  searchPlaceholder: string;
  showShortcut?: boolean;
  headerExtras?: React.ReactNode;
  user: { initials: string; name: string; role: string };
  logoutLabel: string;
  onLogout: () => void;
  children: React.ReactNode;
};

/** Sidebar + top bar frame shared by the agency dashboard and the admin console. */
export function Shell(p: ShellProps) {
  const lang = useLang();
  const rtl = lang === 'ar';
  const pathname = usePathname();
  const router = useRouter();

  const switchLang = () => {
    const seg = pathname.split('/');
    seg[1] = rtl ? 'en' : 'ar';
    router.push(seg.join('/'));
  };

  return (
    <div className={`mk mk-${p.variant}`} dir={rtl ? 'rtl' : 'ltr'} lang={lang}>
      <div style={{ display: 'flex', flexWrap: 'wrap', minHeight: '100vh', background: '#F4F6F8' }}>
        <aside style={{ flex: '1 1 248px', maxWidth: '100%', background: '#FFFFFF', borderInlineEnd: '1px solid #E4E7EC', padding: '18px 14px 24px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 8px 14px' }}>
            <div style={{ width: 34, height: 34, borderRadius: 9, background: '#0E6B63', color: '#FFFFFF', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: rtl ? 17 : 16 }}>{rtl ? 'م' : 'M'}</div>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <span style={{ fontWeight: 700, fontSize: 16, letterSpacing: rtl ? undefined : '.04em', color: '#101828' }}>{rtl ? 'مارك' : 'MARK'}</span>
              <span style={{ fontSize: 12, color: '#475467' }}>{p.brandSub}</span>
            </div>
            {p.envBadge && <span className="pill p-ok" style={{ marginInlineStart: 'auto', fontSize: 11 }}>{p.envBadge}</span>}
          </div>

          {p.workspace && (
            <button className="btn" style={{ justifyContent: 'space-between', height: rtl ? 50 : 48, marginBottom: 8, padding: '0 10px' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ width: 28, height: 28, borderRadius: 7, background: '#1D2939', color: '#FFFFFF', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 600 }}>{p.workspace.initials}</span>
                <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: rtl ? 1.35 : 1.25 }}>
                  <span style={{ fontWeight: 600, color: '#101828', fontSize: 13.5 }}>{p.workspace.name}</span>
                  <span style={{ fontSize: 11.5, color: '#475467' }}>{p.workspace.plan}</span>
                </span>
              </span>
              <Icon name="updown" small />
            </button>
          )}

          {p.nav.map((g, gi) => (
            <div key={gi} style={{ display: 'contents' }}>
              {g.label && <div className="nav-label">{g.label}</div>}
              {g.items.map((it) => {
                const href = `/${lang}${it.href}`;
                const on = pathname === href || pathname.startsWith(href + '/');
                return (
                  <Link key={it.href} href={href} className={on ? 'nav-item on' : 'nav-item'} aria-current={on ? 'page' : undefined}>
                    <Icon name={it.icon} />
                    {it.label}
                    {it.count && <span className={it.alert ? 'cnt alert' : 'cnt'}>{it.count}</span>}
                  </Link>
                );
              })}
            </div>
          ))}

          {p.sidebarFooter}
        </aside>

        <div style={{ flex: '999 1 560px', minWidth: 0, display: 'flex', flexDirection: 'column' }}>
          <header style={{ background: '#FFFFFF', borderBottom: '1px solid #E4E7EC', padding: '12px 32px', display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 12 }}>
            <label style={{ flex: '1 1 280px', maxWidth: 520, display: 'flex', alignItems: 'center', gap: 8, height: 40, padding: '0 12px', border: '1px solid #D0D5DD', borderRadius: 9, color: '#475467', background: '#FFFFFF' }}>
              <Icon name="search" />
              <input type="search" placeholder={p.searchPlaceholder} aria-label={rtl ? 'بحث' : 'Search'} style={{ border: 0, outline: 0, font: 'inherit', fontSize: 14, flex: 1, minWidth: 0, color: '#101828', background: 'transparent' }} />
              {p.showShortcut && <span className="mono" style={{ border: '1px solid #E4E7EC', borderRadius: 5, padding: '0 6px', fontSize: 11.5, color: '#475467' }}>⌘K</span>}
            </label>
            <div style={{ marginInlineStart: 'auto', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              <button className="btn" onClick={switchLang} aria-label={rtl ? 'Switch to English' : 'Switch language'}>{rtl ? 'English' : 'العربية'}</button>
              {p.headerExtras}
              <button className="btn" aria-label={rtl ? 'الإشعارات' : 'Notifications'} style={{ width: 40, height: 40, padding: 0, justifyContent: 'center', position: 'relative' }}>
                <Icon name="bell" />
                <span style={{ position: 'absolute', top: 8, insetInlineEnd: 9, width: 8, height: 8, borderRadius: '50%', background: '#D9480F', border: '2px solid #FFFFFF' }} />
              </button>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingInlineStart: 8, borderInlineStart: '1px solid #E4E7EC', marginInlineStart: 4 }}>
                <div className="av" style={{ background: '#DCEBE8', color: '#0A4F49' }}>{p.user.initials}</div>
                <div style={{ display: 'flex', flexDirection: 'column', lineHeight: rtl ? 1.35 : 1.25 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 600, color: '#101828' }}>{p.user.name}</span>
                  <span style={{ fontSize: 12, color: '#475467' }}>{p.user.role}</span>
                </div>
                <button className="btn btn-ghost btn-sm" onClick={p.onLogout} aria-label={p.logoutLabel} title={p.logoutLabel} style={{ padding: '0 6px' }}>
                  <Icon name="logout" small style={rtl ? { transform: 'scaleX(-1)' } : undefined} />
                </button>
              </div>
            </div>
          </header>

          <main style={{ padding: '28px 32px 48px', display: 'flex', flexDirection: 'column', gap: 24, width: '100%', maxWidth: 1400 }}>
            {p.children}
          </main>
        </div>
      </div>
    </div>
  );
}

/** "Omar Nasser" → "ON"; Arabic names keep a space between letters ("ع ن"), as in the design. */
export function initialsOf(name?: string) {
  if (!name) return '';
  return name.split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0]).join(rtlSafeSep(name)).toUpperCase();
}
function rtlSafeSep(name: string) {
  return /[؀-ۿ]/.test(name) ? ' ' : '';
}
