// CMS editors: the complex package editor + simpler blog/page/vehicle editors

// ---- Rich text toolbar mock (visual only) ----
const RichTextField = ({ label, value, onChange, rows = 10, hint }) => (
  <div>
    {label && <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 6 }}>{label}</div>}
    <div style={{ border: '1px solid #eae4d2', borderRadius: 10, background: 'white', overflow: 'hidden' }}>
      <div style={{ padding: '8px 10px', borderBottom: '1px solid #eae4d2', display: 'flex', gap: 4, flexWrap: 'wrap', background: '#FBFAF4' }}>
        {[
          ['heading-1', 'H1'], ['heading-2', 'H2'], ['bold', 'B'], ['italic', 'I'], ['underline', 'U'],
          ['list', null], ['list-ordered', null], ['quote', null], ['link', null], ['image', null], ['code', null]
        ].map(([ic, t], i) => (
          <button key={i} style={{ padding: '5px 8px', borderRadius: 6, fontSize: 12, color: '#3a3a33', fontWeight: 600 }}
            onMouseEnter={e => e.currentTarget.style.background = '#EFEADA'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            {t || <Icon name={ic} size={13} />}
          </button>
        ))}
        <div style={{ marginLeft: 'auto', fontSize: 11, color: '#a39d8a', alignSelf: 'center' }}>Markdown supported</div>
      </div>
      <textarea value={value || ''} onChange={e => onChange(e.target.value)} rows={rows}
        style={{ width: '100%', border: 0, outline: 0, padding: 16, fontSize: 14, fontFamily: 'Geist', lineHeight: 1.6, resize: 'vertical', background: 'white' }} />
    </div>
    {hint && <div style={{ fontSize: 12, color: '#8a8573', marginTop: 4 }}>{hint}</div>}
  </div>
);

// ---- Repeater (inclusions/exclusions/features) ----
const Repeater = ({ label, items = [], onChange, placeholder = 'Add item', hint }) => {
  const [draft, setDraft] = useState('');
  const add = () => { if (draft.trim()) { onChange([...items, draft.trim()]); setDraft(''); } };
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 6 }}>{label}</div>
      <div style={{ display: 'grid', gap: 6 }}>
        {items.map((t, i) => (
          <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'center', background: 'white', border: '1px solid #eae4d2', borderRadius: 8, padding: '6px 10px' }}>
            <Icon name="check" size={13} style={{ color: 'var(--green)' }} />
            <input value={t} onChange={e => { const next = [...items]; next[i] = e.target.value; onChange(next); }} style={{ flex: 1, border: 0, outline: 0, fontSize: 13, background: 'transparent' }} />
            <button onClick={() => onChange(items.filter((_, j) => j !== i))} style={{ color: '#c9826c', padding: 4 }}><Icon name="x" size={13} /></button>
          </div>
        ))}
        <div style={{ display: 'flex', gap: 6 }}>
          <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()} placeholder={placeholder} style={{ flex: 1, border: '1px dashed #d4cdbb', background: 'transparent', borderRadius: 8, padding: '8px 10px', fontSize: 13, outline: 'none' }} />
          <Btn kind="ghost" size="sm" icon="plus" onClick={add}>Add</Btn>
        </div>
      </div>
      {hint && <div style={{ fontSize: 12, color: '#8a8573', marginTop: 4 }}>{hint}</div>}
    </div>
  );
};

// ---- PACKAGE EDITOR ----
const CmsPackageEditor = ({ state, setState, cmsRoute, setCmsRoute }) => {
  const existing = cmsRoute.id !== 'new' && state.packages.find(p => p.id === cmsRoute.id);
  const [form, setForm] = useState(existing || {
    id: 'pkg' + Date.now(),
    title: '', slug: '', category: 'inbound', destination: '',
    duration: '', durationDays: 1, priceFrom: 0, rating: 5, reviews: 0,
    featured: false, status: 'draft', tags: [],
    hero: 'https://images.unsplash.com/photo-1518544801976-3e188ea7cce9?w=1600&q=80',
    gallery: [], short: '', description: '',
    itinerary: [{ day: 1, title: '', text: '' }],
    inclusions: [], exclusions: [], pricing: [{ label: 'Per pax', price: 0 }],
    created: new Date().toISOString().slice(0, 10),
  });
  const [section, setSection] = useState('basics');
  const { show, node } = useToast();
  const isNew = cmsRoute.id === 'new';

  const set = (patch) => setForm(f => ({ ...f, ...patch }));

  const save = (nextStatus) => {
    const next = { ...form, status: nextStatus || form.status, slug: form.slug || slugify(form.title) };
    setState(s => ({
      ...s,
      packages: isNew ? [next, ...s.packages] : s.packages.map(p => p.id === next.id ? next : p),
    }));
    show(isNew ? 'Package created.' : 'Package updated.');
    if (isNew) setCmsRoute({ route: 'packages' });
  };

  const sections = [
    { id: 'basics', label: 'Basics', icon: 'info' },
    { id: 'media', label: 'Photos & media', icon: 'image' },
    { id: 'itinerary', label: 'Itinerary', icon: 'list' },
    { id: 'pricing', label: 'Pricing', icon: 'tag' },
    { id: 'inex', label: 'Inclusions', icon: 'check-circle' },
    { id: 'publish', label: 'Publish', icon: 'send' },
  ];

  return (
    <>
      <div style={{ padding: '16px 28px', borderBottom: '1px solid #eae4d2', background: 'white', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap', position: 'sticky', top: 57, zIndex: 5 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <button onClick={() => setCmsRoute({ route: 'packages' })} style={{ color: '#5a5544', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}><Icon name="arrow-left" size={14} /> Back</button>
          <div style={{ borderLeft: '1px solid #eae4d2', paddingLeft: 16 }}>
            <div style={{ fontSize: 11, color: '#8a8573', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{isNew ? 'New package' : 'Edit package'}</div>
            <div style={{ fontFamily: 'Fraunces', fontSize: 20, letterSpacing: '-0.015em' }}>{form.title || 'Untitled package'}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <CmsStatusBadge status={form.status} />
          <Btn kind="ghost" onClick={() => save('draft')}>Save draft</Btn>
          <Btn kind="primary" icon="send" onClick={() => save('published')}>{form.status === 'published' ? 'Update' : 'Publish'}</Btn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr 320px', gap: 24, padding: '24px 28px', alignItems: 'start' }}>
        <nav style={{ position: 'sticky', top: 140 }}>
          {sections.map(s => (
            <button key={s.id} onClick={() => setSection(s.id)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 8, fontSize: 13, fontWeight: section === s.id ? 600 : 500, background: section === s.id ? 'white' : 'transparent', color: section === s.id ? 'var(--accent)' : '#3a3a33', textAlign: 'left', border: section === s.id ? '1px solid #eae4d2' : '1px solid transparent', marginBottom: 4 }}>
              <Icon name={s.icon} size={14} />
              {s.label}
            </button>
          ))}
        </nav>

        <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 28, minHeight: 400 }}>
          {section === 'basics' && <div style={{ display: 'grid', gap: 16 }}>
            <h3 style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em', marginBottom: 4 }}>Basics</h3>
            <Input label="Package title" value={form.title} onChange={v => set({ title: v, slug: form.slug || slugify(v) })} required placeholder="e.g. Bako National Park Day Trip" />
            <Input label="URL slug" value={form.slug} onChange={v => set({ slug: v })} prefix="/tours/" hint="Auto-generated from title. Edit if needed." />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Select label="Category" value={form.category} onChange={v => set({ category: v })} options={[{ value: 'inbound', label: 'Inbound (Sarawak)' }, { value: 'outbound', label: 'Outbound' }]} required />
              <Input label="Destination" value={form.destination} onChange={v => set({ destination: v })} placeholder="e.g. Bako, Sarawak" required />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
              <Input label="Duration (display)" value={form.duration} onChange={v => set({ duration: v })} placeholder="3 days, 2 nights" />
              <Input label="Duration days" type="number" value={form.durationDays} onChange={v => set({ durationDays: parseFloat(v) || 0 })} />
              <Input label="Price from (RM)" type="number" value={form.priceFrom} onChange={v => set({ priceFrom: parseFloat(v) || 0 })} prefix="RM" />
            </div>
            <Textarea label="Short description" value={form.short} onChange={v => set({ short: v })} rows={2} hint="Shown on listing cards. Keep it to 1–2 sentences." />
            <RichTextField label="Full description" value={form.description} onChange={v => set({ description: v })} rows={6} />
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 6 }}>Tags</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {form.tags.map((t, i) => (
                  <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', background: '#EFEADA', borderRadius: 999, fontSize: 12 }}>
                    {t}
                    <button onClick={() => set({ tags: form.tags.filter((_, j) => j !== i) })} style={{ color: '#8a8573' }}><Icon name="x" size={11} /></button>
                  </span>
                ))}
                <input placeholder="+ Add tag (enter)" onKeyDown={e => { if (e.key === 'Enter' && e.target.value.trim()) { set({ tags: [...form.tags, e.target.value.trim()] }); e.target.value = ''; } }} style={{ border: '1px dashed #d4cdbb', borderRadius: 999, padding: '4px 12px', fontSize: 12, background: 'transparent', outline: 'none' }} />
              </div>
            </div>
          </div>}

          {section === 'media' && <div style={{ display: 'grid', gap: 16 }}>
            <h3 style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em' }}>Photos & media</h3>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 6 }}>Hero image</div>
              <div style={{ border: '2px dashed #d4cdbb', borderRadius: 12, padding: 24, textAlign: 'center', background: '#FBFAF4' }}>
                {form.hero ? (
                  <>
                    <div style={{ borderRadius: 8, overflow: 'hidden', maxHeight: 260, marginBottom: 12 }}><Img src={form.hero} style={{ maxHeight: 260 }} /></div>
                    <Btn kind="ghost" size="sm" icon="upload">Replace image</Btn>
                  </>
                ) : (
                  <>
                    <Icon name="image-plus" size={32} style={{ color: '#a39d8a' }} />
                    <div style={{ fontSize: 14, marginTop: 10 }}>Drop image here or click to browse</div>
                    <div style={{ fontSize: 12, color: '#8a8573', marginTop: 4 }}>JPG, PNG or WebP. Max 10MB.</div>
                  </>
                )}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 6 }}>Gallery ({form.gallery.length})</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
                {form.gallery.map((g, i) => (
                  <div key={i} style={{ position: 'relative', borderRadius: 8, overflow: 'hidden' }}>
                    <Img src={g} ratio="4/3" />
                    <button onClick={() => set({ gallery: form.gallery.filter((_, j) => j !== i) })} style={{ position: 'absolute', top: 6, right: 6, width: 24, height: 24, borderRadius: '50%', background: 'rgba(0,0,0,0.7)', color: 'white', display: 'grid', placeItems: 'center' }}>
                      <Icon name="x" size={12} />
                    </button>
                  </div>
                ))}
                <button style={{ border: '2px dashed #d4cdbb', borderRadius: 8, aspectRatio: '4/3', color: '#8a8573', fontSize: 13, background: '#FBFAF4', display: 'grid', placeItems: 'center' }}>
                  <div><Icon name="plus" size={20} /><div style={{ marginTop: 4, fontSize: 11 }}>Add photos</div></div>
                </button>
              </div>
            </div>
          </div>}

          {section === 'itinerary' && <div style={{ display: 'grid', gap: 16 }}>
            <h3 style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em' }}>Day-by-day itinerary</h3>
            {form.itinerary.map((d, i) => (
              <div key={i} style={{ border: '1px solid #eae4d2', borderRadius: 12, padding: 16, background: '#FBFAF4' }}>
                <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 10 }}>
                  <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--accent)', color: 'white', display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 600 }}>{d.day}</div>
                  <div style={{ fontSize: 12, color: '#8a8573' }}>Day {d.day}</div>
                  <button onClick={() => set({ itinerary: form.itinerary.filter((_, j) => j !== i) })} style={{ marginLeft: 'auto', color: '#c9826c', padding: 4 }}><Icon name="trash-2" size={14} /></button>
                </div>
                <Input label="Title" value={d.title} onChange={v => { const next = [...form.itinerary]; next[i] = { ...next[i], title: v }; set({ itinerary: next }); }} placeholder="e.g. Arrive Mulu · Deer Cave" />
                <Textarea label="Description" value={d.text} onChange={v => { const next = [...form.itinerary]; next[i] = { ...next[i], text: v }; set({ itinerary: next }); }} rows={3} style={{ marginTop: 10 }} />
              </div>
            ))}
            <Btn kind="ghost" icon="plus" onClick={() => set({ itinerary: [...form.itinerary, { day: form.itinerary.length + 1, title: '', text: '' }] })}>Add day</Btn>
          </div>}

          {section === 'pricing' && <div style={{ display: 'grid', gap: 16 }}>
            <h3 style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em' }}>Pricing tiers</h3>
            <div style={{ fontSize: 13, color: '#5a5544' }}>Add group pricing tiers. The lowest tier is shown as "From" on the public site.</div>
            {form.pricing.map((p, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 160px 40px', gap: 10, alignItems: 'end' }}>
                <Input label={i === 0 ? 'Tier label' : ''} value={p.label} onChange={v => { const next = [...form.pricing]; next[i] = { ...next[i], label: v }; set({ pricing: next }); }} placeholder="e.g. 2 pax (twin)" />
                <Input label={i === 0 ? 'Price per pax' : ''} type="number" value={p.price} onChange={v => { const next = [...form.pricing]; next[i] = { ...next[i], price: parseFloat(v) || 0 }; set({ pricing: next }); }} prefix="RM" />
                <button onClick={() => set({ pricing: form.pricing.filter((_, j) => j !== i) })} style={{ height: 42, color: '#c9826c' }}><Icon name="trash-2" size={15} /></button>
              </div>
            ))}
            <Btn kind="ghost" size="sm" icon="plus" onClick={() => set({ pricing: [...form.pricing, { label: '', price: 0 }] })}>Add tier</Btn>
          </div>}

          {section === 'inex' && <div style={{ display: 'grid', gap: 24 }}>
            <h3 style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em' }}>Inclusions & exclusions</h3>
            <Repeater label="What's included" items={form.inclusions} onChange={v => set({ inclusions: v })} placeholder="e.g. Hotel pickup & drop-off" />
            <Repeater label="What's NOT included" items={form.exclusions} onChange={v => set({ exclusions: v })} placeholder="e.g. Travel insurance" />
          </div>}

          {section === 'publish' && <div style={{ display: 'grid', gap: 16 }}>
            <h3 style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em' }}>Publish settings</h3>
            <Select label="Status" value={form.status} onChange={v => set({ status: v })} options={[{ value: 'draft', label: 'Draft' }, { value: 'published', label: 'Published' }]} />
            <Toggle value={form.featured} onChange={v => set({ featured: v })} label="Feature on homepage" hint="Featured packages appear in the homepage grid (up to 4)." />
            <div style={{ padding: 16, background: '#F7F5F0', borderRadius: 10, fontSize: 13 }}>
              <div style={{ fontWeight: 600, marginBottom: 4 }}>SEO preview</div>
              <div style={{ color: '#1a0dab', fontSize: 14 }}>{form.title || 'Your package title'} — PXS Travel</div>
              <div style={{ color: '#006621', fontSize: 12 }}>projekx.com/tours/{form.slug || 'your-slug'}</div>
              <div style={{ color: '#545454', fontSize: 12, marginTop: 2 }}>{form.short || 'Your short description will appear here as the meta description.'}</div>
            </div>
          </div>}
        </div>

        {/* Live preview panel */}
        <aside style={{ position: 'sticky', top: 140 }}>
          <div style={{ fontSize: 11, color: '#8a8573', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>Live preview</div>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 14, overflow: 'hidden' }}>
            <Img src={form.hero} ratio="4/3" />
            <div style={{ padding: 16 }}>
              <div style={{ fontSize: 12, color: '#5a5544', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="map-pin" size={11} />{form.destination || 'Destination'}</div>
              <h3 style={{ fontFamily: 'Fraunces', fontSize: 18, marginTop: 6, letterSpacing: '-0.015em', lineHeight: 1.2 }}>{form.title || 'Package title'}</h3>
              <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 10, borderTop: '1px solid #eee7d6' }}>
                <div>
                  <div style={{ fontSize: 10, color: '#8a8573', textTransform: 'uppercase' }}>From</div>
                  <div style={{ fontFamily: 'Fraunces', fontSize: 18 }}>{fmtMYR(form.priceFrom || 0)}</div>
                </div>
                <Pill tone={form.category === 'inbound' ? 'green' : 'blue'}>{form.category}</Pill>
              </div>
            </div>
          </div>
          <div style={{ marginTop: 12, fontSize: 11, color: '#8a8573', textAlign: 'center' }}>Card preview updates live as you type.</div>
        </aside>
      </div>
      {node}
    </>
  );
};

// ---- BLOG EDITOR ----
const CmsBlogEditor = ({ state, setState, cmsRoute, setCmsRoute }) => {
  const existing = cmsRoute.id !== 'new' && state.blogs.find(b => b.id === cmsRoute.id);
  const [form, setForm] = useState(existing || {
    id: 'b' + Date.now(), title: '', slug: '', author: 'Sarah Lim',
    date: new Date().toISOString().slice(0, 10), status: 'draft',
    category: 'Destinations', tags: [],
    featuredImage: 'https://images.unsplash.com/photo-1518544801976-3e188ea7cce9?w=1600&q=80',
    excerpt: '', body: '',
  });
  const { show, node } = useToast();
  const isNew = cmsRoute.id === 'new';
  const save = (nextStatus) => {
    const next = { ...form, status: nextStatus || form.status, slug: form.slug || slugify(form.title) };
    setState(s => ({ ...s, blogs: isNew ? [next, ...s.blogs] : s.blogs.map(b => b.id === next.id ? next : b) }));
    show(isNew ? 'Post created.' : 'Post updated.');
    if (isNew) setCmsRoute({ route: 'blogs' });
  };

  return (
    <>
      <div style={{ padding: '16px 28px', borderBottom: '1px solid #eae4d2', background: 'white', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, position: 'sticky', top: 57, zIndex: 5 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <button onClick={() => setCmsRoute({ route: 'blogs' })} style={{ color: '#5a5544', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}><Icon name="arrow-left" size={14} /> Back</button>
          <div style={{ fontFamily: 'Fraunces', fontSize: 20 }}>{isNew ? 'New blog post' : 'Edit post'}</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <CmsStatusBadge status={form.status} />
          <Btn kind="ghost" onClick={() => save('draft')}>Save draft</Btn>
          <Btn kind="primary" icon="send" onClick={() => save('published')}>Publish</Btn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 24, padding: '24px 28px' }}>
        <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 28 }}>
          <Input label="Title" value={form.title} onChange={v => setForm({ ...form, title: v, slug: form.slug || slugify(v) })} required />
          <div style={{ marginTop: 14 }}><Input label="URL slug" value={form.slug} onChange={v => setForm({ ...form, slug: v })} prefix="/blog/" /></div>
          <div style={{ marginTop: 14 }}><Textarea label="Excerpt" value={form.excerpt} onChange={v => setForm({ ...form, excerpt: v })} rows={2} hint="Shown on the blog listing page." /></div>
          <div style={{ marginTop: 14 }}><RichTextField label="Body" value={form.body} onChange={v => setForm({ ...form, body: v })} rows={14} /></div>
        </div>
        <aside style={{ display: 'grid', gap: 14 }}>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20, display: 'grid', gap: 14 }}>
            <h4 style={{ fontSize: 13, fontWeight: 600 }}>Publish</h4>
            <Select label="Status" value={form.status} onChange={v => setForm({ ...form, status: v })} options={['draft', 'published']} />
            <Input label="Publish date" type="date" value={form.date} onChange={v => setForm({ ...form, date: v })} />
            <Select label="Author" value={form.author} onChange={v => setForm({ ...form, author: v })} options={state.users.map(u => u.name)} />
            <Input label="Category" value={form.category} onChange={v => setForm({ ...form, category: v })} />
          </div>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20 }}>
            <h4 style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Featured image</h4>
            <div style={{ borderRadius: 8, overflow: 'hidden', marginBottom: 10 }}><Img src={form.featuredImage} ratio="16/10" /></div>
            <Input label="" value={form.featuredImage} onChange={v => setForm({ ...form, featuredImage: v })} placeholder="Image URL" />
          </div>
        </aside>
      </div>
      {node}
    </>
  );
};

// ---- PAGE EDITOR ----
const CmsPageEditor = ({ state, setState, cmsRoute, setCmsRoute }) => {
  const existing = cmsRoute.id !== 'new' && state.pages.find(p => p.id === cmsRoute.id);
  const [form, setForm] = useState(existing || {
    id: 'p' + Date.now(), title: '', slug: '', status: 'draft',
    updated: new Date().toISOString().slice(0, 10), inMenu: false,
    metaTitle: '', metaDesc: '', body: '',
  });
  const { show, node } = useToast();
  const isNew = cmsRoute.id === 'new';
  const save = (nextStatus) => {
    const next = { ...form, status: nextStatus || form.status, slug: form.slug || slugify(form.title), updated: new Date().toISOString().slice(0, 10) };
    setState(s => ({ ...s, pages: isNew ? [next, ...s.pages] : s.pages.map(p => p.id === next.id ? next : p) }));
    show(isNew ? 'Page created.' : 'Page updated.');
    if (isNew) setCmsRoute({ route: 'pages' });
  };

  return (
    <>
      <div style={{ padding: '16px 28px', borderBottom: '1px solid #eae4d2', background: 'white', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, position: 'sticky', top: 57, zIndex: 5 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <button onClick={() => setCmsRoute({ route: 'pages' })} style={{ color: '#5a5544', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}><Icon name="arrow-left" size={14} /> Back</button>
          <div style={{ fontFamily: 'Fraunces', fontSize: 20 }}>{isNew ? 'New page' : 'Edit page'}</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <CmsStatusBadge status={form.status} />
          <Btn kind="ghost" onClick={() => save('draft')}>Save draft</Btn>
          <Btn kind="primary" icon="send" onClick={() => save('published')}>Publish</Btn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 24, padding: '24px 28px' }}>
        <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 28, display: 'grid', gap: 14 }}>
          <Input label="Page title" value={form.title} onChange={v => setForm({ ...form, title: v, slug: form.slug || slugify(v) })} required />
          <Input label="URL slug" value={form.slug} onChange={v => setForm({ ...form, slug: v })} prefix="/" />
          <RichTextField label="Page content" value={form.body} onChange={v => setForm({ ...form, body: v })} rows={14} />
        </div>
        <aside style={{ display: 'grid', gap: 14 }}>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20, display: 'grid', gap: 14 }}>
            <h4 style={{ fontSize: 13, fontWeight: 600 }}>Publish</h4>
            <Select label="Status" value={form.status} onChange={v => setForm({ ...form, status: v })} options={['draft', 'published']} />
            <Toggle value={form.inMenu} onChange={v => setForm({ ...form, inMenu: v })} label="Show in main navigation" />
          </div>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20, display: 'grid', gap: 14 }}>
            <h4 style={{ fontSize: 13, fontWeight: 600 }}>SEO</h4>
            <Input label="Meta title" value={form.metaTitle} onChange={v => setForm({ ...form, metaTitle: v })} />
            <Textarea label="Meta description" value={form.metaDesc} onChange={v => setForm({ ...form, metaDesc: v })} rows={3} hint={(form.metaDesc || '').length + '/160 characters'} />
          </div>
        </aside>
      </div>
      {node}
    </>
  );
};

// ---- VEHICLE EDITOR ----
const CmsVehicleEditor = ({ state, setState, cmsRoute, setCmsRoute }) => {
  const existing = cmsRoute.id !== 'new' && state.vehicles.find(v => v.id === cmsRoute.id);
  const [form, setForm] = useState(existing || {
    id: 'v' + Date.now(), name: '', type: 'Sedan', capacity: 4, luggage: 2, rate: 0,
    available: true, status: 'draft', photo: 'https://images.unsplash.com/photo-1590362891991-f776e747a588?w=1000&q=80',
    features: [], description: '',
  });
  const { show, node } = useToast();
  const isNew = cmsRoute.id === 'new';
  const save = (nextStatus) => {
    const next = { ...form, status: nextStatus || form.status };
    setState(s => ({ ...s, vehicles: isNew ? [next, ...s.vehicles] : s.vehicles.map(v => v.id === next.id ? next : v) }));
    show(isNew ? 'Vehicle created.' : 'Vehicle updated.');
    if (isNew) setCmsRoute({ route: 'vehicles' });
  };

  return (
    <>
      <div style={{ padding: '16px 28px', borderBottom: '1px solid #eae4d2', background: 'white', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, position: 'sticky', top: 57, zIndex: 5 }}>
        <button onClick={() => setCmsRoute({ route: 'vehicles' })} style={{ color: '#5a5544', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}><Icon name="arrow-left" size={14} /> Back</button>
        <div style={{ display: 'flex', gap: 8 }}>
          <Btn kind="ghost" onClick={() => save('draft')}>Save draft</Btn>
          <Btn kind="primary" icon="send" onClick={() => save('published')}>Publish</Btn>
        </div>
      </div>
      <div style={{ padding: '24px 28px', display: 'grid', gridTemplateColumns: '1fr 320px', gap: 24 }}>
        <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 28, display: 'grid', gap: 14 }}>
          <Input label="Vehicle name" value={form.name} onChange={v => setForm({ ...form, name: v })} required />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
            <Select label="Type" value={form.type} onChange={v => setForm({ ...form, type: v })} options={['Sedan', 'SUV', 'MPV', 'Van', 'Bus', '4WD']} />
            <Input label="Capacity (pax)" type="number" value={form.capacity} onChange={v => setForm({ ...form, capacity: parseInt(v) || 0 })} />
            <Input label="Luggage (bags)" type="number" value={form.luggage} onChange={v => setForm({ ...form, luggage: parseInt(v) || 0 })} />
          </div>
          <Input label="Daily rate" type="number" value={form.rate} onChange={v => setForm({ ...form, rate: parseFloat(v) || 0 })} prefix="RM" suffix="/ day" />
          <Textarea label="Description" value={form.description} onChange={v => setForm({ ...form, description: v })} rows={3} />
          <Repeater label="Features / specs" items={form.features} onChange={v => setForm({ ...form, features: v })} placeholder="e.g. Air-conditioned" />
        </div>
        <aside style={{ display: 'grid', gap: 14 }}>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20 }}>
            <h4 style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Photo</h4>
            <div style={{ borderRadius: 8, overflow: 'hidden', marginBottom: 10 }}><Img src={form.photo} ratio="16/10" /></div>
            <Input label="" value={form.photo} onChange={v => setForm({ ...form, photo: v })} placeholder="Image URL" />
          </div>
          <div style={{ background: 'white', border: '1px solid #eae4d2', borderRadius: 12, padding: 20, display: 'grid', gap: 14 }}>
            <Toggle value={form.available} onChange={v => setForm({ ...form, available: v })} label="Available for booking" />
            <Select label="Status" value={form.status} onChange={v => setForm({ ...form, status: v })} options={['draft', 'published']} />
          </div>
        </aside>
      </div>
      {node}
    </>
  );
};

Object.assign(window, { CmsPackageEditor, CmsBlogEditor, CmsPageEditor, CmsVehicleEditor });
