// CMS admin shell: sidebar + topbar + dashboard

const CmsShell = ({ state, cmsRoute, setCmsRoute, children }) => {
  const nav = [
    { group: 'Overview', items: [
      { id: 'dashboard', label: 'Dashboard', icon: 'layout-dashboard' },
    ]},
    { group: 'Content', items: [
      { id: 'packages', label: 'Tour packages', icon: 'compass', count: state.packages.length },
      { id: 'vehicles', label: 'Vehicles', icon: 'car', count: state.vehicles.length },
      { id: 'blogs', label: 'Blog', icon: 'book-open', count: state.blogs.length },
      { id: 'pages', label: 'Pages', icon: 'file-text', count: state.pages.length },
    ]},
    { group: 'Operations', items: [
      { id: 'inquiries', label: 'Inquiries', icon: 'mail', count: state.inquiries.filter(i => i.status === 'new').length, badge: 'new' },
      { id: 'menu', label: 'Navigation', icon: 'menu' },
    ]},
    { group: 'Admin', items: [
      { id: 'users', label: 'Users', icon: 'users' },
      { id: 'settings', label: 'Settings', icon: 'settings' },
    ]},
  ];

  return (
    <div data-pxs-cms-shell style={{ display: 'flex', minHeight: '100vh', background: '#F7F5F0', fontSize: 14 }}>
      {/* Sidebar */}
      <aside data-pxs-cms-sidebar style={{ width: 260, background: 'white', borderRight: '1px solid #eae4d2', padding: '20px 16px', position: 'sticky', top: 0, height: '100vh', overflowY: 'auto', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 8px 20px', borderBottom: '1px solid #eae4d2' }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--accent)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'Fraunces', fontWeight: 600 }}>P</div>
          <div data-pxs-cms-brand-text>
            <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em' }}>PXS Travel</div>
            <div style={{ fontSize: 11, color: '#8a8573' }}>Admin · v2.4.1</div>
          </div>
        </div>
        {nav.map(g => (
          <div key={g.group} style={{ marginTop: 20 }}>
            <div data-pxs-cms-group style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#a39d8a', padding: '0 8px 8px' }}>{g.group}</div>
            {g.items.map(it => {
              const active = cmsRoute.route === it.id || cmsRoute.route?.startsWith(it.id + '-');
              return (
                <button key={it.id} onClick={() => setCmsRoute({ route: it.id })} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '9px 10px', borderRadius: 8, background: active ? 'rgba(232,93,47,0.08)' : 'transparent', color: active ? 'var(--accent)' : '#3a3a33', fontSize: 13.5, fontWeight: active ? 600 : 500, textAlign: 'left', marginBottom: 2 }}>
                  <Icon name={it.icon} size={15} />
                  <span data-pxs-cms-label style={{ flex: 1 }}>{it.label}</span>
                  {it.count != null && <span data-pxs-cms-count style={{ fontSize: 11, color: it.badge && it.count > 0 ? 'var(--accent)' : '#a39d8a', background: it.badge && it.count > 0 ? 'rgba(232,93,47,0.12)' : 'transparent', padding: it.badge && it.count > 0 ? '2px 7px' : 0, borderRadius: 999, fontWeight: 600 }}>{it.count}</span>}
                </button>
              );
            })}
          </div>
        ))}
      </aside>

      {/* Main */}
      <main style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <header data-pxs-cms-topbar style={{ background: 'white', borderBottom: '1px solid #eae4d2', padding: '12px 28px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 20, position: 'sticky', top: 0, zIndex: 10 }}>
          <div data-pxs-cms-search style={{ display: 'flex', alignItems: 'center', gap: 14, flex: 1 }}>
            <div style={{ position: 'relative', flex: 1, maxWidth: 400 }}>
              <Icon name="search" size={14} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#8a8573' }} />
              <input placeholder="Search packages, pages, inquiries..." style={{ width: '100%', padding: '8px 12px 8px 34px', border: '1px solid #eae4d2', borderRadius: 8, background: '#F7F5F0', fontSize: 13, outline: 'none' }} />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button style={{ padding: 8, color: '#5a5544' }}><Icon name="bell" size={16} /></button>
            <button style={{ padding: 8, color: '#5a5544' }}><Icon name="help-circle" size={16} /></button>
            <div style={{ width: 1, height: 20, background: '#eae4d2' }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--green)', color: 'white', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 600 }}>PL</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>Peter Lau</div>
                <div style={{ fontSize: 11, color: '#8a8573' }}>Admin</div>
              </div>
            </div>
          </div>
        </header>

        <div data-pxs-cms-content style={{ flex: 1 }}>
          {children}
        </div>
      </main>
    </div>
  );
};

// -------- DASHBOARD --------
const CmsDashboard = ({ state, setCmsRoute }) => {
  const newInquiries = state.inquiries.filter(i => i.status === 'new').length;
  const published = state.packages.filter(p => p.status === 'published').length;
  const drafts = state.packages.filter(p => p.status === 'draft').length;
  const blogDrafts = state.blogs.filter(b => b.status === 'draft').length;

  const stats = [
    { label: 'Tour packages', value: state.packages.length, delta: '+2 this month', icon: 'compass' },
    { label: 'Published', value: published, delta: drafts + ' in draft', icon: 'check-circle' },
    { label: 'New inquiries', value: newInquiries, delta: 'needs attention', icon: 'mail', highlight: true },
    { label: 'Blog posts', value: state.blogs.length, delta: blogDrafts + ' in draft', icon: 'book-open' },
  ];

  return (
    <div style={{ padding: '28px 28px 60px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 28, flexWrap: 'wrap', gap: 16 }} data-pxs-dash-head>
        <div>
          <div style={{ fontSize: 11, color: '#8a8573', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{new Date().toLocaleDateString('en-MY', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</div>
          <h1 style={{ fontSize: 30, fontFamily: 'Fraunces', letterSpacing: '-0.02em', marginTop: 4, fontWeight: 400 }}>Selamat pagi, Peter.</h1>
          <div style={{ fontSize: 14, color: '#5a5544', marginTop: 4 }}>You have <span style={{ color: 'var(--accent)', fontWeight: 600 }}>{newInquiries} new inquiries</span> waiting for a reply.</div>
        </div>
        <div data-pxs-cms-quickactions style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <Btn kind="primary" icon="plus" onClick={() => setCmsRoute({ route: 'packages-edit', id: 'new' })}>New package</Btn>
          <Btn kind="ghost" icon="plus" onClick={() => setCmsRoute({ route: 'blogs-edit', id: 'new' })}>New blog post</Btn>
          <Btn kind="ghost" icon="plus" onClick={() => setCmsRoute({ route: 'pages-edit', id: 'new' })}>New page</Btn>
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 14, marginBottom: 28 }}>
        {stats.map(s => (
          <div key={s.label} style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20, position: 'relative', overflow: 'hidden' }}>
            {s.highlight && <div style={{ position: 'absolute', top: 0, left: 0, width: 3, height: '100%', background: 'var(--accent)' }} />}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start' }}>
              <div style={{ fontSize: 12, color: '#8a8573', fontWeight: 500 }}>{s.label}</div>
              <Icon name={s.icon} size={16} style={{ color: s.highlight ? 'var(--accent)' : '#a39d8a' }} />
            </div>
            <div style={{ fontFamily: 'Fraunces', fontSize: 38, letterSpacing: '-0.02em', marginTop: 8, lineHeight: 1 }}>{s.value}</div>
            <div style={{ fontSize: 12, color: '#8a8573', marginTop: 8 }}>{s.delta}</div>
          </div>
        ))}
      </div>

      <div data-pxs-dash-cols style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 20 }}>
        {/* Recent inquiries */}
        <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid #eae4d2', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontSize: 15, fontWeight: 600, fontFamily: 'Geist' }}>Recent inquiries</h3>
            <button onClick={() => setCmsRoute({ route: 'inquiries' })} style={{ fontSize: 13, color: 'var(--accent)', fontWeight: 500 }}>View all →</button>
          </div>
          <div>
            {state.inquiries.slice(0, 6).map(i => (
              <div key={i.id} onClick={() => setCmsRoute({ route: 'inquiries', openId: i.id })} style={{ padding: '14px 20px', borderBottom: '1px solid #f3ecd9', display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'center', flex: 1, minWidth: 0 }}>
                  <div style={{ width: 34, height: 34, borderRadius: '50%', background: '#EFEADA', color: '#5a5544', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 600, flexShrink: 0 }}>{i.name.split(' ').map(x => x[0]).join('').slice(0,2)}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                      {i.name}
                      {i.status === 'new' && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} />}
                    </div>
                    <div style={{ fontSize: 12, color: '#8a8573', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{i.service} · {i.message.slice(0, 70)}...</div>
                  </div>
                </div>
                <div style={{ fontSize: 11, color: '#a39d8a', flexShrink: 0, marginLeft: 10 }}>{relTime(i.date)}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Activity */}
        <div>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20, marginBottom: 14 }}>
            <h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>Quick links</h3>
            <div style={{ display: 'grid', gap: 8 }}>
              {[
                { route: 'packages', icon: 'compass', label: 'Manage tour packages' },
                { route: 'blogs', icon: 'book-open', label: 'Blog posts' },
                { route: 'menu', icon: 'menu', label: 'Edit site navigation' },
                { route: 'settings', icon: 'settings', label: 'Site settings' },
              ].map(x => (
                <button key={x.route} onClick={() => setCmsRoute({ route: x.route })} style={{ padding: '10px 12px', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#3a3a33', textAlign: 'left', transition: 'background .15s' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#F7F5F0'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <Icon name={x.icon} size={14} style={{ color: '#8a8573' }} />
                  {x.label}
                  <Icon name="arrow-right" size={12} style={{ marginLeft: 'auto', color: '#a39d8a' }} />
                </button>
              ))}
            </div>
          </div>

          <div style={{ background: 'var(--green-deep)', color: '#F5EEDE', borderRadius: 12, padding: 20 }}>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', opacity: 0.7 }}>This month</div>
            <div style={{ fontFamily: 'Fraunces', fontSize: 34, letterSpacing: '-0.02em', marginTop: 8, lineHeight: 1 }}>147</div>
            <div style={{ fontSize: 13, marginTop: 4, opacity: 0.8 }}>inquiries received · +22% vs last month</div>
            <div style={{ marginTop: 14, display: 'flex', gap: 2, alignItems: 'end', height: 40 }}>
              {[45, 52, 38, 60, 48, 72, 66, 80, 58, 90, 72, 85].map((h, i) => (
                <div key={i} style={{ flex: 1, height: h + '%', background: i > 7 ? '#E85D2F' : 'rgba(245,238,222,0.35)', borderRadius: 2 }} />
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ---- Shared CMS chrome bits ----
const CmsPageHeader = ({ title, subtitle, breadcrumb, actions }) => (
  <div style={{ padding: '24px 28px 20px', borderBottom: '1px solid #eae4d2', background: 'white' }}>
    {breadcrumb && <div style={{ fontSize: 12, color: '#8a8573', marginBottom: 6 }}>{breadcrumb}</div>}
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', gap: 16, flexWrap: 'wrap' }}>
      <div>
        <h1 style={{ fontSize: 26, fontFamily: 'Fraunces', letterSpacing: '-0.02em', fontWeight: 400 }}>{title}</h1>
        {subtitle && <div style={{ fontSize: 14, color: '#5a5544', marginTop: 4 }}>{subtitle}</div>}
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{actions}</div>
    </div>
  </div>
);

const CmsStatusBadge = ({ status }) => {
  const map = {
    published: { tone: 'green', label: 'Published' },
    draft: { tone: 'neutral', label: 'Draft' },
    new: { tone: 'orange', label: 'New' },
    read: { tone: 'blue', label: 'Read' },
    responded: { tone: 'green', label: 'Responded' },
  };
  const m = map[status] || { tone: 'neutral', label: status };
  return <Pill tone={m.tone}>{m.label}</Pill>;
};

Object.assign(window, { CmsShell, CmsDashboard, CmsPageHeader, CmsStatusBadge });
