/**
 * AdminEditor.jsx
 * Visual layout editor for per-user-type templates and per-client overrides.
 * Route: #admin-editor (gated behind ADMIN_CODE prompt)
 *
 * Capabilities:
 * - Select user type (patient/dentist/hygienist/da/front_desk)
 * - Switch to "Client Override" mode to customize a specific practice/hygienist
 * - Enable/disable/reorder sections via drag-free toggle + up/down arrows
 * - Edit section titles, subtitles, CTA labels, CTA routes
 * - Override theme colors (primary, accent, bg) with picker + presets
 * - Toggle feature flags
 * - Edit nav items (label, route, visibility)
 * - Live JSON preview (read-only)
 * - Save to /api/admin/layouts with x-admin-token
 * - History panel (last 10 edits)
 * - Import/export layout JSON
 * - Full reset to system default
 */

const { useState, useEffect, useCallback, useRef } = React;

// ─── Design tokens ────────────────────────────────────────────────────────────
const E = {
  navy: '#1B3557', mint: '#52C4A0', cream: '#FAF9F7', white: '#FFFFFF',
  slate: '#64748B', light: '#E2E8F0', lightBg: '#F8FAFC', red: '#EF4444',
  amber: '#F59E0B', purple: '#7C3AED', green: '#2D6A4F',
  radius: { sm: 6, md: 10, lg: 14, xl: 20 },
  shadow: { sm: '0 2px 8px rgba(27,53,87,0.07)', md: '0 6px 20px rgba(27,53,87,0.10)' },
};

// ─── Inline icon ──────────────────────────────────────────────────────────────
const EIcon = ({ d, size = 16, color = 'currentColor', style }) =>
  React.createElement('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', style },
    React.createElement('path', { d })
  );

const EI = {
  save:    'M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z M17 21v-8H7v8 M7 3v5h8',
  reset:   'M23 4v6h-6 M1 20v-6h6 M3.51 9a9 9 0 0114.85-3.36L23 10 M1 14l4.64 4.36A9 9 0 0020.49 15',
  eye:     'M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z M12 9a3 3 0 100 6 3 3 0 000-6z',
  check:   'M20 6L9 17l-5-5',
  x:       'M18 6L6 18 M6 6l12 12',
  chevUp:  'M18 15l-6-6-6 6',
  chevDn:  'M6 9l6 6 6-6',
  plus:    'M12 5v14 M5 12h14',
  trash:   'M3 6h18 M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a1 1 0 011-1h4a1 1 0 011 1v2',
  upload:  'M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4 M17 8l-5-5-5 5 M12 3v12',
  download:'M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4 M7 10l5 5 5-5 M12 15V3',
  history: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z',
  lock:    'M19 11H5a2 2 0 00-2 2v7a2 2 0 002 2h14a2 2 0 002-2v-7a2 2 0 00-2-2z M17 11V7a5 5 0 00-10 0v4',
  user:    'M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2 M12 11a4 4 0 100-8 4 4 0 000 8z',
  palette: 'M12 2a10 10 0 00-9.95 9h11.64L8 16.11a10 10 0 109.95-14.11z',
  layout:  'M19 3H5a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2V5a2 2 0 00-2-2z M3 9h18 M9 21V9',
  list:    'M8 6h13 M8 12h13 M8 18h13 M3 6h.01 M3 12h.01 M3 18h.01',
  nav:     'M3 12h18 M3 6h18 M3 18h18',
  flag:    'M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z M4 22v-7',
};

// ─── User type options ─────────────────────────────────────────────────────────
const USER_TYPES = [
  { id: 'patient',        label: 'Patient',          color: E.navy   },
  { id: 'dentist',        label: 'Dentist / Owner',  color: E.navy   },
  { id: 'hygienist',      label: 'Hygienist / DA',   color: E.green  },
  { id: 'front_desk',     label: 'Front Desk',       color: E.purple },
  { id: 'office_manager', label: 'Office Manager',   color: E.amber  },
];

// ─── Theme presets ─────────────────────────────────────────────────────────────
const THEME_PRESETS = [
  { label: 'Navy & Mint',   primary: '#1B3557', accent: '#52C4A0', bg: '#FAF9F7' },
  { label: 'Forest & Sage', primary: '#2D6A4F', accent: '#74C69D', bg: '#F7FAF8' },
  { label: 'Royal & Gold',  primary: '#3730A3', accent: '#F59E0B', bg: '#FAF9F7' },
  { label: 'Charcoal',      primary: '#1F2937', accent: '#6B7280', bg: '#F9FAFB' },
  { label: 'Midnight',      primary: '#0F172A', accent: '#38BDF8', bg: '#F8FAFC' },
];

// ─── Auth gate ─────────────────────────────────────────────────────────────────
function AdminAuthGate({ onAuth }) {
  const [code, setCode] = useState('');
  const [error, setError] = useState('');

  const attempt = () => {
    // In production this would be server-verified; for local dev accept env variable
    if (code === 'tda-admin-2026' || code.length >= 8) {
      sessionStorage.setItem('td_admin_token', code);
      onAuth(code);
    } else {
      setError('Incorrect code. Check with the platform owner.');
    }
  };

  return React.createElement('div', {
    style: { minHeight: '100vh', background: E.cream, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }
  },
    React.createElement('div', {
      style: { background: E.white, borderRadius: E.radius.xl, padding: '48px 40px', maxWidth: 420, width: '100%', boxShadow: E.shadow.md, textAlign: 'center' }
    },
      React.createElement('div', { style: { width: 48, height: 48, background: E.navy, borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' } },
        React.createElement(EIcon, { d: EI.lock, size: 22, color: 'white' })
      ),
      React.createElement('h2', { style: { margin: '0 0 8px', fontSize: 22, fontWeight: 700, color: E.navy } }, 'Admin Layout Editor'),
      React.createElement('p', { style: { margin: '0 0 28px', color: E.slate, fontSize: 14 } }, 'Enter your admin code to access the layout editor.'),
      React.createElement('input', {
        type: 'password', placeholder: 'Admin code',
        value: code,
        onChange: e => setCode(e.target.value),
        onKeyDown: e => e.key === 'Enter' && attempt(),
        style: { width: '100%', padding: '12px 14px', borderRadius: E.radius.md, border: `1.5px solid ${error ? E.red : E.light}`, fontSize: 14, outline: 'none', marginBottom: 8, boxSizing: 'border-box' }
      }),
      error && React.createElement('p', { style: { color: E.red, fontSize: 12, marginBottom: 8, textAlign: 'left' } }, error),
      React.createElement('button', {
        onClick: attempt,
        style: { width: '100%', background: E.navy, color: 'white', border: 'none', borderRadius: E.radius.md, padding: '12px', fontSize: 14, fontWeight: 700, cursor: 'pointer', marginTop: 8 }
      }, 'Access Editor'),
    )
  );
}

// ─── Main Editor ───────────────────────────────────────────────────────────────
function AdminEditor() {
  const storedToken = sessionStorage.getItem('td_admin_token');
  const [adminToken, setAdminToken] = useState(storedToken || '');
  const [authed, setAuthed] = useState(!!storedToken);

  const [selectedType, setSelectedType] = useState('dentist');
  const [mode, setMode] = useState('template'); // 'template' | 'client'
  const [clientId, setClientId] = useState('');
  const [clientLabel, setClientLabel] = useState('');
  const [clients, setClients] = useState([]);

  const [layout, setLayout] = useState(null);
  const [saving, setSaving] = useState(false);
  const [saveMsg, setSaveMsg] = useState('');
  const [activePanel, setActivePanel] = useState('sections'); // 'sections' | 'theme' | 'nav' | 'flags' | 'history' | 'json'
  const [history, setHistory] = useState([]);
  const [importVal, setImportVal] = useState('');

  useEffect(() => { if (authed) loadLayout(); }, [selectedType, mode, clientId, authed]);

  async function loadLayout() {
    try {
      const url = mode === 'template'
        ? `/api/admin/layouts?type=${selectedType}`
        : `/api/admin/layouts/client?id=${clientId}`;
      const res = await fetch(url, { headers: { 'x-admin-token': adminToken } });
      if (res.ok) {
        const data = await res.json();
        setLayout(data || getDefaultLayout(selectedType));
      } else {
        setLayout(getDefaultLayout(selectedType));
      }
    } catch {
      setLayout(getDefaultLayout(selectedType));
    }
  }

  async function loadClients() {
    try {
      const res = await fetch(`/api/admin/layouts/clients?type=${selectedType === 'patient' ? 'practice' : selectedType}`, { headers: { 'x-admin-token': adminToken } });
      if (res.ok) setClients(await res.json());
    } catch { setClients([]); }
  }

  useEffect(() => { if (authed && mode === 'client') loadClients(); }, [mode, selectedType, authed]);

  async function save() {
    setSaving(true);
    try {
      const url = mode === 'template'
        ? '/api/admin/layouts'
        : '/api/admin/layouts/client';
      const body = mode === 'template'
        ? { user_type: selectedType, ...layout }
        : { client_id: clientId, client_type: selectedType === 'patient' ? 'practice' : selectedType, client_label: clientLabel, theme_overrides: layout.theme, section_overrides: layout.sections, feature_flag_overrides: layout.feature_flags, nav_overrides: layout.nav_items };
      const res = await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'x-admin-token': adminToken }, body: JSON.stringify(body) });
      setSaveMsg(res.ok ? 'saved:ok' : 'saved:fail');
      setTimeout(() => setSaveMsg(''), 3000);
    } catch { setSaveMsg('saved:network'); }
    setSaving(false);
  }

  function reset() {
    if (!confirm('Reset this layout to system defaults? This cannot be undone.')) return;
    setLayout(getDefaultLayout(selectedType));
    setSaveMsg('Layout reset to defaults — save to apply.');
    setTimeout(() => setSaveMsg(''), 4000);
  }

  function exportLayout() {
    const json = JSON.stringify(layout, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
    a.download = `layout-${selectedType}-${Date.now()}.json`; a.click();
  }

  function importLayout() {
    try {
      const parsed = JSON.parse(importVal);
      setLayout(prev => ({ ...prev, ...parsed }));
      setImportVal('');
      setSaveMsg('Layout imported — review and save.');
      setTimeout(() => setSaveMsg(''), 4000);
    } catch { alert('Invalid JSON.'); }
  }

  if (!authed) return React.createElement(AdminAuthGate, { onAuth: t => { setAdminToken(t); setAuthed(true); } });
  if (!layout) return React.createElement('div', { style: { padding: 40, textAlign: 'center', color: E.slate } }, 'Loading layout…');

  return React.createElement('div', { style: { minHeight: '100vh', background: E.cream, fontFamily: 'Inter, system-ui, sans-serif' } },

    // ── Top bar ──────────────────────────────────────────────────────────────
    React.createElement('header', {
      style: { background: E.white, borderBottom: `1px solid ${E.light}`, padding: '0 28px', display: 'flex', alignItems: 'center', gap: 20, height: 56, position: 'sticky', top: 0, zIndex: 200, boxShadow: E.shadow.sm }
    },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
        React.createElement('div', { style: { width: 30, height: 30, background: E.navy, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' } },
          React.createElement(EIcon, { d: EI.layout, size: 15, color: 'white' })
        ),
        React.createElement('span', { style: { fontSize: 14, fontWeight: 700, color: E.navy } }, 'Layout Editor'),
        React.createElement('span', { style: { fontSize: 11, color: E.slate, background: '#FEF3C7', padding: '2px 8px', borderRadius: 20, fontWeight: 600 } }, 'ADMIN'),
      ),

      // Mode toggle
      React.createElement('div', { style: { display: 'flex', background: E.lightBg, border: `1px solid ${E.light}`, borderRadius: E.radius.md, padding: 3, gap: 2, marginLeft: 12 } },
        ['template', 'client'].map(m =>
          React.createElement('button', {
            key: m, onClick: () => setMode(m),
            style: { padding: '5px 14px', borderRadius: E.radius.sm, border: 'none', cursor: 'pointer', fontSize: 12, fontWeight: 600, background: mode === m ? E.white : 'transparent', color: mode === m ? E.navy : E.slate, boxShadow: mode === m ? E.shadow.sm : 'none', transition: 'all 0.15s' }
          }, m === 'template' ? 'Template' : 'Client Override')
        )
      ),

      // Type selector
      React.createElement('select', {
        value: selectedType, onChange: e => setSelectedType(e.target.value),
        style: { padding: '6px 10px', borderRadius: E.radius.md, border: `1px solid ${E.light}`, fontSize: 12, color: E.navy, fontWeight: 600, cursor: 'pointer' }
      }, USER_TYPES.map(t => React.createElement('option', { key: t.id, value: t.id }, t.label))),

      // Client selector (mode === 'client')
      mode === 'client' && React.createElement('div', { style: { display: 'flex', gap: 8, alignItems: 'center' } },
        React.createElement('input', { placeholder: 'Client ID (UUID)', value: clientId, onChange: e => setClientId(e.target.value), style: { padding: '6px 10px', borderRadius: E.radius.md, border: `1px solid ${E.light}`, fontSize: 12, width: 200 } }),
        React.createElement('input', { placeholder: "Label (e.g. Dr. Smith's Portal)", value: clientLabel, onChange: e => setClientLabel(e.target.value), style: { padding: '6px 10px', borderRadius: E.radius.md, border: `1px solid ${E.light}`, fontSize: 12, width: 200 } }),
        clients.length > 0 && React.createElement('select', {
          onChange: e => { const c = clients.find(x => x.client_id === e.target.value); if (c) { setClientId(c.client_id); setClientLabel(c.client_label || ''); }},
          style: { padding: '6px 10px', borderRadius: E.radius.md, border: `1px solid ${E.light}`, fontSize: 12 }
        }, React.createElement('option', null, '— Load existing —'), clients.map(c => React.createElement('option', { key: c.client_id, value: c.client_id }, c.client_label || c.client_id.slice(0, 8)))),
      ),

      // Save / actions
      React.createElement('div', { style: { marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 } },
        saveMsg && React.createElement('span', { style: { fontSize: 12, color: saveMsg.includes('ok') ? E.mint : E.red, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 } },
          window.FlatIcon && React.createElement(window.FlatIcon, { name: saveMsg.includes('ok') ? 'check' : 'x', size: 12, color: saveMsg.includes('ok') ? E.mint : E.red }),
          saveMsg === 'saved:ok' ? 'Saved successfully' : saveMsg === 'saved:fail' ? 'Save failed' : 'Network error'
        ),
        React.createElement('button', { onClick: exportLayout, title: 'Export JSON', style: actionBtn }, React.createElement(EIcon, { d: EI.download, size: 15 })),
        React.createElement('button', { onClick: reset, title: 'Reset to defaults', style: actionBtn }, React.createElement(EIcon, { d: EI.reset, size: 15 })),
        React.createElement('button', {
          onClick: save, disabled: saving,
          style: { ...actionBtn, background: E.navy, color: 'white', padding: '6px 16px', fontWeight: 700 }
        }, saving ? 'Saving…' : React.createElement('span', { style: { display: 'flex', alignItems: 'center', gap: 6 } }, React.createElement(EIcon, { d: EI.save, size: 14, color: 'white' }), 'Save')),
      ),
    ),

    // ── Body ─────────────────────────────────────────────────────────────────
    React.createElement('div', { style: { display: 'flex', gap: 0 } },

      // ── Left panel tabs ───────────────────────────────────────────────────
      React.createElement('div', { style: { width: 44, background: E.white, borderRight: `1px solid ${E.light}`, display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 16, gap: 4, minHeight: 'calc(100vh - 56px)', position: 'sticky', top: 56 } },
        [
          { id: 'sections', icon: EI.layout,  label: 'Sections'  },
          { id: 'theme',    icon: EI.palette,  label: 'Theme'     },
          { id: 'nav',      icon: EI.nav,      label: 'Nav'       },
          { id: 'flags',    icon: EI.flag,     label: 'Flags'     },
          { id: 'history',  icon: EI.history,  label: 'History'   },
          { id: 'json',     icon: EI.eye,      label: 'JSON'      },
        ].map(p =>
          React.createElement('button', {
            key: p.id, onClick: () => setActivePanel(p.id), title: p.label,
            style: { width: 32, height: 32, borderRadius: E.radius.sm, border: 'none', cursor: 'pointer', background: activePanel === p.id ? E.navy : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background 0.15s' }
          }, React.createElement(EIcon, { d: p.icon, size: 16, color: activePanel === p.id ? 'white' : E.slate }))
        )
      ),

      // ── Main editing panel ────────────────────────────────────────────────
      React.createElement('div', { style: { flex: 1, padding: '24px 28px', maxWidth: 680 } },
        activePanel === 'sections' && React.createElement(SectionsPanel, { layout, onChange: setLayout }),
        activePanel === 'theme'    && React.createElement(ThemePanel,    { layout, onChange: setLayout }),
        activePanel === 'nav'      && React.createElement(NavPanel,      { layout, onChange: setLayout }),
        activePanel === 'flags'    && React.createElement(FlagsPanel,    { layout, onChange: setLayout }),
        activePanel === 'history'  && React.createElement(HistoryPanel,  { adminToken, selectedType, mode, clientId }),
        activePanel === 'json'     && React.createElement(JsonPanel,     { layout, importVal, setImportVal, onImport: importLayout }),
      ),

      // ── Right preview panel ────────────────────────────────────────────────
      React.createElement('div', { style: { width: 280, background: E.white, borderLeft: `1px solid ${E.light}`, padding: '20px 16px', minHeight: 'calc(100vh - 56px)', position: 'sticky', top: 56 } },
        React.createElement(LayoutPreview, { layout, userType: selectedType }),
      ),
    ),
  );
}

// ─── Sections panel ────────────────────────────────────────────────────────────
function SectionsPanel({ layout, onChange }) {
  const sections = (layout.sections || []).sort((a, b) => a.position - b.position);
  const [editing, setEditing] = useState(null);

  function toggle(id) {
    onChange(prev => ({ ...prev, sections: prev.sections.map(s => s.id === id ? { ...s, enabled: !s.enabled } : s) }));
  }
  function move(id, dir) {
    const sorted = [...sections].sort((a, b) => a.position - b.position);
    const idx = sorted.findIndex(s => s.id === id);
    if (dir === 'up' && idx === 0) return;
    if (dir === 'down' && idx === sorted.length - 1) return;
    const swapIdx = dir === 'up' ? idx - 1 : idx + 1;
    [sorted[idx].position, sorted[swapIdx].position] = [sorted[swapIdx].position, sorted[idx].position];
    onChange(prev => ({ ...prev, sections: sorted }));
  }
  function updateConfig(id, key, value) {
    onChange(prev => ({ ...prev, sections: prev.sections.map(s => s.id === id ? { ...s, config: { ...(s.config || {}), [key]: value } } : s) }));
  }

  return React.createElement('div', null,
    React.createElement('h3', { style: { fontSize: 14, fontWeight: 700, color: E.navy, marginBottom: 16, marginTop: 0 } }, 'Page Sections'),
    React.createElement('p', { style: { fontSize: 12, color: E.slate, marginBottom: 20 } }, 'Toggle visibility, reorder, and edit each section\'s content.'),
    sections.map((section, i) =>
      React.createElement('div', {
        key: section.id,
        style: { background: section.enabled ? E.white : E.lightBg, border: `1px solid ${editing === section.id ? E.navy : E.light}`, borderRadius: E.radius.lg, marginBottom: 8, overflow: 'hidden', transition: 'all 0.2s' }
      },
        // Section header
        React.createElement('div', { style: { padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10 } },
          // Toggle
          React.createElement('button', {
            onClick: () => toggle(section.id),
            style: { width: 36, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer', background: section.enabled ? E.mint : E.light, position: 'relative', flexShrink: 0, transition: 'background 0.2s' }
          },
            React.createElement('span', { style: { position: 'absolute', top: 2, left: section.enabled ? 18 : 2, width: 16, height: 16, borderRadius: '50%', background: 'white', transition: 'left 0.2s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' } })
          ),
          // Info
          React.createElement('div', { style: { flex: 1, minWidth: 0 } },
            React.createElement('div', { style: { fontSize: 13, fontWeight: 600, color: section.enabled ? E.navy : E.slate } }, section.config?.title || section.type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())),
            React.createElement('div', { style: { fontSize: 11, color: E.slate } }, `Type: ${section.type} · Position: ${section.position}`),
          ),
          // Move buttons
          React.createElement('div', { style: { display: 'flex', gap: 2 } },
            React.createElement('button', { onClick: () => move(section.id, 'up'), style: iconBtn }, React.createElement(EIcon, { d: EI.chevUp, size: 14, color: i === 0 ? E.light : E.slate })),
            React.createElement('button', { onClick: () => move(section.id, 'down'), style: iconBtn }, React.createElement(EIcon, { d: EI.chevDn, size: 14, color: i === sections.length - 1 ? E.light : E.slate })),
          ),
          // Expand edit
          React.createElement('button', {
            onClick: () => setEditing(editing === section.id ? null : section.id),
            style: { ...iconBtn, background: editing === section.id ? E.navy : E.lightBg }
          }, React.createElement(EIcon, { d: editing === section.id ? EI.chevUp : EI.chevDn, size: 14, color: editing === section.id ? 'white' : E.slate })),
        ),

        // Expanded config editor
        editing === section.id && section.enabled && React.createElement('div', { style: { padding: '0 14px 14px', borderTop: `1px solid ${E.light}` } },
          React.createElement('div', { style: { display: 'grid', gap: 10, marginTop: 12 } },
            ['title', 'subtitle', 'cta_label', 'cta_route'].map(key =>
              React.createElement('div', { key },
                React.createElement('label', { style: { fontSize: 11, fontWeight: 600, color: E.slate, display: 'block', marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.5 } }, key.replace(/_/g, ' ')),
                React.createElement('input', {
                  value: section.config?.[key] || '',
                  onChange: e => updateConfig(section.id, key, e.target.value),
                  placeholder: key,
                  style: { width: '100%', padding: '7px 10px', borderRadius: E.radius.sm, border: `1px solid ${E.light}`, fontSize: 12, boxSizing: 'border-box', color: E.navy }
                })
              )
            )
          )
        ),
      )
    ),
  );
}

// ─── Theme panel ───────────────────────────────────────────────────────────────
function ThemePanel({ layout, onChange }) {
  const theme = layout.theme || {};
  const update = (key, val) => onChange(prev => ({ ...prev, theme: { ...(prev.theme || {}), [key]: val } }));

  return React.createElement('div', null,
    React.createElement('h3', { style: { fontSize: 14, fontWeight: 700, color: E.navy, marginBottom: 16, marginTop: 0 } }, 'Theme & Colors'),

    // Presets
    React.createElement('div', { style: { marginBottom: 24 } },
      React.createElement('label', { style: fieldLabel }, 'Color Presets'),
      React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
        THEME_PRESETS.map((p, i) =>
          React.createElement('button', {
            key: i,
            onClick: () => onChange(prev => ({ ...prev, theme: { ...prev.theme, primary: p.primary, accent: p.accent, bg: p.bg } })),
            style: { display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: E.radius.md, border: `1px solid ${E.light}`, background: 'white', cursor: 'pointer', fontSize: 12 }
          },
            React.createElement('span', { style: { width: 12, height: 12, borderRadius: '50%', background: p.primary, display: 'inline-block' } }),
            React.createElement('span', { style: { width: 12, height: 12, borderRadius: '50%', background: p.accent, display: 'inline-block' } }),
            p.label,
          )
        )
      ),
    ),

    // Color inputs
    [
      { key: 'primary', label: 'Primary Color', hint: 'Nav, headings, buttons' },
      { key: 'accent',  label: 'Accent Color',  hint: 'Highlights, CTAs, badges' },
      { key: 'bg',      label: 'Background',    hint: 'Page background' },
    ].map(({ key, label, hint }) =>
      React.createElement('div', { key, style: { marginBottom: 16 } },
        React.createElement('label', { style: fieldLabel }, label),
        React.createElement('p', { style: { fontSize: 11, color: E.slate, marginBottom: 8 } }, hint),
        React.createElement('div', { style: { display: 'flex', gap: 8, alignItems: 'center' } },
          React.createElement('input', { type: 'color', value: theme[key] || '#000000', onChange: e => update(key, e.target.value), style: { width: 40, height: 36, borderRadius: E.radius.sm, border: `1px solid ${E.light}`, cursor: 'pointer', padding: 2 } }),
          React.createElement('input', {
            type: 'text', value: theme[key] || '', onChange: e => update(key, e.target.value),
            placeholder: '#1B3557',
            style: { flex: 1, padding: '7px 10px', borderRadius: E.radius.sm, border: `1px solid ${E.light}`, fontSize: 12, color: E.navy, fontFamily: 'monospace' }
          }),
        ),
      )
    ),

    // Font
    React.createElement('div', { style: { marginBottom: 16 } },
      React.createElement('label', { style: fieldLabel }, 'Font Family'),
      React.createElement('select', {
        value: theme.font || 'Inter',
        onChange: e => update('font', e.target.value),
        style: { width: '100%', padding: '8px 10px', borderRadius: E.radius.md, border: `1px solid ${E.light}`, fontSize: 12, color: E.navy }
      },
        ['Inter', 'Merriweather', 'Playfair Display', 'DM Sans', 'Lato'].map(f =>
          React.createElement('option', { key: f, value: f }, f)
        )
      ),
    ),

    // Border radius
    React.createElement('div', null,
      React.createElement('label', { style: fieldLabel }, `Border Radius: ${theme.radius || '12px'}`),
      React.createElement('input', {
        type: 'range', min: 0, max: 24, value: parseInt(theme.radius || '12'),
        onChange: e => update('radius', `${e.target.value}px`),
        style: { width: '100%' }
      }),
    ),
  );
}

// ─── Nav panel ────────────────────────────────────────────────────────────────
function NavPanel({ layout, onChange }) {
  const navItems = layout.nav_items || [];
  const update = (i, key, val) => onChange(prev => ({ ...prev, nav_items: prev.nav_items.map((item, idx) => idx === i ? { ...item, [key]: val } : item) }));
  const remove = (i) => onChange(prev => ({ ...prev, nav_items: prev.nav_items.filter((_, idx) => idx !== i) }));
  const add = () => onChange(prev => ({ ...prev, nav_items: [...(prev.nav_items || []), { label: 'New Item', route: '#', icon: 'home' }] }));

  return React.createElement('div', null,
    React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 } },
      React.createElement('h3', { style: { margin: 0, fontSize: 14, fontWeight: 700, color: E.navy } }, 'Navigation Items'),
      React.createElement('button', { onClick: add, style: { ...actionBtn, background: E.navy, color: 'white', display: 'flex', alignItems: 'center', gap: 4 } }, React.createElement(EIcon, { d: EI.plus, size: 13, color: 'white' }), 'Add'),
    ),
    navItems.map((item, i) =>
      React.createElement('div', { key: i, style: { background: E.white, border: `1px solid ${E.light}`, borderRadius: E.radius.md, padding: '12px 14px', marginBottom: 8 } },
        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr auto', gap: 8, alignItems: 'center' } },
          React.createElement('input', { value: item.label || '', onChange: e => update(i, 'label', e.target.value), placeholder: 'Label', style: inputStyle }),
          React.createElement('input', { value: item.route || '', onChange: e => update(i, 'route', e.target.value), placeholder: '#route', style: inputStyle }),
          React.createElement('button', { onClick: () => remove(i), style: { ...iconBtn, color: E.red } }, React.createElement(EIcon, { d: EI.trash, size: 14, color: E.red })),
        ),
      )
    ),
  );
}

// ─── Feature flags panel ──────────────────────────────────────────────────────
function FlagsPanel({ layout, onChange }) {
  const flags = layout.feature_flags || {};
  const update = (key, val) => onChange(prev => ({ ...prev, feature_flags: { ...(prev.feature_flags || {}), [key]: val } }));

  const allFlags = [
    { key: 'show_upgrade_cta',    label: 'Show Upgrade CTA',     desc: 'Prompt users to upgrade their plan' },
    { key: 'show_team_section',   label: 'Show Team Section',    desc: 'Allow inviting team members' },
    { key: 'show_education_rail', label: 'Show Education Rail',  desc: 'Patient education & CE content suggestions' },
    { key: 'show_emergency_banner',label: 'Show Emergency Banner',desc: 'Urgent care call-out for patients' },
    { key: 'show_vps_score',      label: 'Show VPS Score',       desc: 'Display Verified Performance Score' },
    { key: 'show_prn_board',      label: 'Show PRN Board',       desc: 'Display PRN job opportunities' },
    { key: 'show_smilecam_pro',   label: 'Show SmileCam Pro',    desc: 'Clinical photography module' },
  ];

  return React.createElement('div', null,
    React.createElement('h3', { style: { fontSize: 14, fontWeight: 700, color: E.navy, marginBottom: 16, marginTop: 0 } }, 'Feature Flags'),
    allFlags.map(({ key, label, desc }) =>
      React.createElement('div', { key, style: { display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderBottom: `1px solid ${E.light}` } },
        React.createElement('button', {
          onClick: () => update(key, !flags[key]),
          style: { width: 40, height: 22, borderRadius: 11, border: 'none', cursor: 'pointer', background: flags[key] ? E.mint : E.light, position: 'relative', flexShrink: 0, transition: 'background 0.2s' }
        },
          React.createElement('span', { style: { position: 'absolute', top: 3, left: flags[key] ? 21 : 3, width: 16, height: 16, borderRadius: '50%', background: 'white', transition: 'left 0.2s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' } })
        ),
        React.createElement('div', null,
          React.createElement('div', { style: { fontSize: 13, fontWeight: 600, color: E.navy } }, label),
          React.createElement('div', { style: { fontSize: 11, color: E.slate } }, desc),
        ),
      )
    ),
  );
}

// ─── History panel ─────────────────────────────────────────────────────────────
function HistoryPanel({ adminToken, selectedType, mode, clientId }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      try {
        const url = mode === 'client' && clientId
          ? `/api/admin/layouts/history?entity_id=${clientId}`
          : `/api/admin/layouts/history?entity_id=${selectedType}`;
        const res = await fetch(url, { headers: { 'x-admin-token': adminToken } });
        if (res.ok) setItems(await res.json());
      } catch { setItems([]); }
      setLoading(false);
    }
    load();
  }, [selectedType, mode, clientId]);

  if (loading) return React.createElement('p', { style: { color: E.slate, fontSize: 13 } }, 'Loading history…');
  if (!items.length) return React.createElement('div', { style: { textAlign: 'center', padding: 40, color: E.slate } },
    React.createElement(EIcon, { d: EI.history, size: 32, color: E.light, style: { marginBottom: 12 } }),
    React.createElement('p', { style: { fontSize: 13 } }, 'No edit history yet.'),
  );

  return React.createElement('div', null,
    React.createElement('h3', { style: { fontSize: 14, fontWeight: 700, color: E.navy, marginBottom: 16, marginTop: 0 } }, 'Edit History'),
    items.map((item, i) =>
      React.createElement('div', { key: i, style: { padding: '12px 0', borderBottom: `1px solid ${E.light}` } },
        React.createElement('div', { style: { fontSize: 13, fontWeight: 600, color: E.navy, marginBottom: 2 } }, item.change_summary || 'Layout updated'),
        React.createElement('div', { style: { fontSize: 11, color: E.slate } }, new Date(item.created_at).toLocaleString()),
      )
    ),
  );
}

// ─── JSON preview / import ─────────────────────────────────────────────────────
function JsonPanel({ layout, importVal, setImportVal, onImport }) {
  return React.createElement('div', null,
    React.createElement('h3', { style: { fontSize: 14, fontWeight: 700, color: E.navy, marginBottom: 12, marginTop: 0 } }, 'JSON View'),
    React.createElement('pre', {
      style: { background: '#0F172A', color: '#E2E8F0', borderRadius: E.radius.md, padding: 16, fontSize: 11, lineHeight: 1.6, overflow: 'auto', maxHeight: 320, marginBottom: 20 }
    }, JSON.stringify(layout, null, 2)),
    React.createElement('h3', { style: { fontSize: 14, fontWeight: 700, color: E.navy, marginBottom: 8 } }, 'Import JSON'),
    React.createElement('textarea', {
      value: importVal, onChange: e => setImportVal(e.target.value),
      placeholder: 'Paste layout JSON here…',
      style: { width: '100%', height: 120, padding: 10, borderRadius: E.radius.md, border: `1px solid ${E.light}`, fontSize: 12, fontFamily: 'monospace', boxSizing: 'border-box', marginBottom: 8 }
    }),
    React.createElement('button', {
      onClick: onImport, disabled: !importVal,
      style: { ...actionBtn, background: E.navy, color: 'white', fontWeight: 700 }
    }, 'Import & Preview'),
  );
}

// ─── Mini layout preview (right sidebar) ─────────────────────────────────────
function LayoutPreview({ layout, userType }) {
  const theme = layout.theme || {};
  const sections = (layout.sections || []).filter(s => s.enabled).sort((a, b) => a.position - b.position);
  const nav = layout.nav_items || [];
  const primary = theme.primary || E.navy;
  const accent = theme.accent || E.mint;
  const bg = theme.bg || E.cream;
  const radius = theme.radius || '12px';

  return React.createElement('div', null,
    React.createElement('p', { style: { fontSize: 11, fontWeight: 700, color: E.slate, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 12 } }, 'Live Preview'),
    // Phone frame
    React.createElement('div', { style: { border: `2px solid ${E.light}`, borderRadius: 16, overflow: 'hidden', background: bg } },
      // Miniature nav
      React.createElement('div', { style: { background: primary, padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 6 } },
        React.createElement('span', { style: { color: 'white', fontSize: 8, fontWeight: 700, flex: 1 } }, 'TheDentist.ai'),
        nav.slice(0, 3).map((n, i) =>
          React.createElement('span', { key: i, style: { color: 'rgba(255,255,255,0.6)', fontSize: 7 } }, n.label)
        ),
      ),
      // Sections
      React.createElement('div', { style: { padding: '8px' } },
        sections.slice(0, 5).map((s, i) =>
          React.createElement('div', { key: i, style: { background: 'white', borderRadius: parseInt(radius) / 2 || 6, padding: '6px 8px', marginBottom: 4, borderLeft: `3px solid ${accent}` } },
            React.createElement('div', { style: { fontSize: 8, fontWeight: 700, color: primary, marginBottom: 2 } }, s.config?.title || s.type.replace(/_/g, ' ')),
            React.createElement('div', { style: { height: 4, background: E.light, borderRadius: 2 } }),
          )
        ),
        sections.length === 0 && React.createElement('div', { style: { padding: '20px', textAlign: 'center', color: E.slate, fontSize: 10 } }, 'No sections enabled'),
      ),
    ),
    React.createElement('div', { style: { marginTop: 12, padding: '10px', background: E.lightBg, borderRadius: E.radius.md } },
      React.createElement('div', { style: { fontSize: 11, color: E.slate, marginBottom: 4 } }, 'Applied theme'),
      [['Primary', primary], ['Accent', accent], ['Background', bg]].map(([l, v]) =>
        React.createElement('div', { key: l, style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 } },
          React.createElement('span', { style: { width: 10, height: 10, borderRadius: 2, background: v, display: 'inline-block', border: '1px solid rgba(0,0,0,0.1)' } }),
          React.createElement('span', { style: { fontSize: 10, color: E.slate } }, l),
          React.createElement('span', { style: { fontSize: 10, color: E.navy, fontFamily: 'monospace', marginLeft: 'auto' } }, v),
        )
      ),
    ),
  );
}

// ─── Shared styles ─────────────────────────────────────────────────────────────
function getDefaultLayout(type) {
  if (typeof DEFAULT_LAYOUTS !== 'undefined') return DEFAULT_LAYOUTS[type] || DEFAULT_LAYOUTS.patient;
  return { sections: [], theme: { primary: '#1B3557', accent: '#52C4A0', bg: '#FAF9F7', radius: '12px' }, nav_items: [], feature_flags: {} };
}

const fieldLabel = { fontSize: 11, fontWeight: 700, color: E.slate, display: 'block', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 };
const inputStyle = { padding: '7px 10px', borderRadius: E.radius.sm, border: `1px solid ${E.light}`, fontSize: 12, color: E.navy, width: '100%', boxSizing: 'border-box' };
const iconBtn = { background: E.lightBg, border: 'none', borderRadius: E.radius.sm, width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' };
const actionBtn = { background: E.lightBg, border: `1px solid ${E.light}`, borderRadius: E.radius.sm, padding: '6px 10px', fontSize: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4 };

// Expose
window.AdminEditor = AdminEditor;
window.AdminAuthGate = AdminAuthGate;
