/* global React, Card, Badge, Button, Icon, ICONS, sb */
console.log('[Services.jsx] v9 start');

const { useState, useEffect, useRef } = React;

const SERV_KEY = uid => 'inbrivvo_services_' + uid;
const CATS_KEY = uid => 'inbrivvo_categories_' + uid;

function loadServices(uid)   { try { return JSON.parse(localStorage.getItem(SERV_KEY(uid)) || '[]'); } catch(e) { return []; } }
function saveServices(uid, arr)  { try { localStorage.setItem(SERV_KEY(uid), JSON.stringify(arr)); } catch(e) {} }
function loadCategories(uid) { try { return JSON.parse(localStorage.getItem(CATS_KEY(uid)) || '[]'); } catch(e) { return []; } }
function saveCategories(uid, arr){ try { localStorage.setItem(CATS_KEY(uid), JSON.stringify(arr)); } catch(e) {} }

function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0;
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}

function fmtPrice(n) {
  var num = parseFloat(n) || 0;
  return 'R$ ' + num.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

var STATUS_MAP = {
  ativo:     { label: 'Ativo',     tone: 'success' },
  pausado:   { label: 'Pausado',   tone: 'warning' },
  arquivado: { label: 'Arquivado', tone: 'neutral'  },
};

var CAT_COLORS = ['#3B82F6','#A855F7','#EC4899','#F97316','#22C55E','#818CF8','#EF4444','#F59E0B','#06B6D4','#84CC16','#F43F5E','#C084FC'];

var CARD_GRADIENTS = [
  'linear-gradient(135deg,#FF6B6B,#FF8E53)',
  'linear-gradient(135deg,#4158D0,#C850C0)',
  'linear-gradient(135deg,#0093E9,#80D0C7)',
  'linear-gradient(135deg,#43E97B,#38F9D7)',
  'linear-gradient(135deg,#FA709A,#FEE140)',
  'linear-gradient(135deg,#A18CD1,#FBC2EB)',
];

function cardGradient(service, categories) {
  var cat = null;
  for (var i = 0; i < categories.length; i++) {
    if (categories[i].id === service.categoryId) { cat = categories[i]; break; }
  }
  if (cat && cat.color) return 'linear-gradient(135deg,' + cat.color + ',' + cat.color + '99)';
  var idx = Math.abs((service.name ? service.name.charCodeAt(0) : 0)) % CARD_GRADIENTS.length;
  return CARD_GRADIENTS[idx];
}

var SUGGESTIONS = [
  { name: 'Identidade Visual',      description: 'Logotipo, paleta de cores, tipografia e guia de marca.', price: 2500 },
  { name: 'Social Media Mensal',    description: 'Gestão e criação de conteúdo para redes sociais.', price: 1800 },
  { name: 'Website Institucional',  description: 'Site responsivo com até 5 páginas.', price: 4500 },
  { name: 'UI/UX Design',           description: 'Interface completa para aplicativo ou sistema web.', price: 3500 },
  { name: 'Campanha de Lançamento', description: 'Peças para lançamento de produto ou serviço.', price: 3200 },
  { name: 'Embalagem',              description: 'Design de embalagem para produto físico.', price: 2200 },
  { name: 'Consultoria de Marca',   description: 'Diagnóstico e direcionamento estratégico de marca.', price: 900 },
  { name: 'Edicao de Video',        description: 'Edição e motion de vídeos para redes sociais.', price: 1200 },
];

var INP = {
  width: '100%', padding: '10px 12px', borderRadius: 8, border: '1px solid var(--border-subtle)',
  background: 'var(--bg-elevated)', color: 'var(--fg-primary)', fontFamily: 'inherit', fontSize: 14,
  outline: 'none', boxSizing: 'border-box',
};
var LBL = { fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-muted)', display: 'block', marginBottom: 6 };

// ─── SvToggle ─────────────────────────────────────────────────────────────────
function SvToggle({ value, onChange }) {
  return (
    <div onClick={() => onChange(!value)} style={{
      width: 44, height: 24, borderRadius: 12, cursor: 'pointer', flexShrink: 0,
      background: value ? '#FF6B6B' : 'var(--bg-elevated)',
      border: '2px solid ' + (value ? '#FF6B6B' : 'var(--border-subtle)'),
      position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: 2, left: value ? 20 : 2, width: 16, height: 16,
        borderRadius: '50%', background: '#fff', transition: 'left 200ms ease',
      }}/>
    </div>
  );
}

// ─── ServiceModal ──────────────────────────────────────────────────────────────
function ServiceModal({ service, categories, onClose, onSave }) {
  var isEdit = !!service;
  var sv = service || {};
  const [form, setForm] = useState({
    name:                 sv.name || '',
    description:          sv.description || '',
    price:                sv.price != null ? String(sv.price) : '',
    categoryId:           sv.categoryId || '',
    status:               sv.status || 'ativo',
    recorrente:           sv.recorrente || false,
    exibirPaginaPublica:  sv.exibirPaginaPublica || false,
    exibirFormularioLeads:sv.exibirFormularioLeads || false,
  });
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [saving, setSaving] = useState(false);
  function set(k, v) { setForm(function(f) { var o = Object.assign({}, f); o[k] = v; return o; }); }

  function handleSave() {
    if (!form.name.trim()) { window.__toast && window.__toast('Nome é obrigatório', { tone: 'danger' }); return; }
    setSaving(true);
    var obj = Object.assign({}, sv, {
      id:                   sv.id || uuid(),
      name:                 form.name.trim(),
      description:          form.description,
      price:                parseFloat(form.price) || 0,
      categoryId:           form.categoryId || null,
      status:               form.status,
      recorrente:           form.recorrente,
      exibirPaginaPublica:  form.exibirPaginaPublica,
      exibirFormularioLeads:form.exibirFormularioLeads,
      createdAt:            sv.createdAt || new Date().toISOString(),
    });
    Promise.resolve(onSave(obj)).then(function() { setSaving(false); });
  }

  var overlayStyle = { position: 'fixed', inset: 0, background: 'rgba(8,12,28,0.65)', backdropFilter: 'blur(6px)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 };
  var panelStyle = { width: 'min(600px,100%)', maxHeight: '92vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 16, boxShadow: '0 24px 64px rgba(0,0,0,0.45)', overflow: 'hidden' };

  return (
    <div onClick={onClose} style={overlayStyle}>
      <div onClick={function(e) { e.stopPropagation(); }} style={panelStyle}>

        <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: 'linear-gradient(135deg,#FF6B6B,#FF8E53)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg viewBox="0 0 24 24" width={20} height={20} fill="none" stroke="#fff" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
            </svg>
          </div>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, flex: 1 }}>{isEdit ? 'Editar Serviço' : 'Novo Serviço'}</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 6 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 24, display: 'flex', flexDirection: 'column', gap: 18 }}>

          {showSuggestions && (
            <div style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: 16 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', marginBottom: 10, textTransform: 'uppercase' }}>Sugestões para estúdios criativos</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {SUGGESTIONS.map(function(s) {
                  return (
                    <div key={s.name} onClick={function() { set('name', s.name); set('description', s.description); set('price', String(s.price)); setShowSuggestions(false); }}
                      style={{ padding: '10px 12px', borderRadius: 8, background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', cursor: 'pointer' }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{s.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>{fmtPrice(s.price)}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          <div>
            <label style={LBL}>Nome do Serviço *</label>
            <input autoFocus value={form.name} onChange={function(e) { set('name', e.target.value); }} placeholder="Ex: Website, Logo Design..." style={INP}/>
          </div>

          <div>
            <label style={LBL}>Descrição</label>
            <textarea value={form.description} onChange={function(e) { set('description', e.target.value); }} placeholder="O que está incluso no serviço" rows={3} style={Object.assign({}, INP, { resize: 'vertical', minHeight: 80, lineHeight: 1.55 })}/>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            <div>
              <label style={LBL}>Preço (R$)</label>
              <input type="number" min="0" step="0.01" value={form.price} onChange={function(e) { set('price', e.target.value); }} placeholder="0,00" style={INP}/>
            </div>
            <div>
              <label style={LBL}>Categoria</label>
              <select value={form.categoryId} onChange={function(e) { set('categoryId', e.target.value); }} style={Object.assign({}, INP, { cursor: 'pointer' })}>
                <option value="">Sem categoria</option>
                {categories.map(function(c) { return <option key={c.id} value={c.id}>{c.name}</option>; })}
              </select>
            </div>
            <div>
              <label style={LBL}>Status</label>
              <select value={form.status} onChange={function(e) { set('status', e.target.value); }} style={Object.assign({}, INP, { cursor: 'pointer' })}>
                <option value="ativo">Ativo</option>
                <option value="pausado">Pausado</option>
                <option value="arquivado">Arquivado</option>
              </select>
            </div>
          </div>

          {[
            { key: 'recorrente',            label: 'Serviço Recorrente',           hint: 'Cobrança mensal, trimestral ou anual' },
            { key: 'exibirPaginaPublica',   label: 'Exibir na Página Pública',     hint: 'Mostrar na sua landing page/portfólio' },
            { key: 'exibirFormularioLeads', label: 'Exibir no Formulário de Leads', hint: 'Disponibilizar no formulário de captação' },
          ].map(function(item) {
            return (
              <div key={item.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', background: 'var(--bg-elevated)', borderRadius: 10, border: '1px solid var(--border-subtle)' }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{item.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>{item.hint}</div>
                </div>
                <SvToggle value={form[item.key]} onChange={function(v) { set(item.key, v); }}/>
              </div>
            );
          })}
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={function() { setShowSuggestions(function(s) { return !s; }); }} style={{ background: 'transparent', border: '1px solid var(--border-subtle)', borderRadius: 8, color: 'var(--fg-secondary)', cursor: 'pointer', padding: '8px 14px', fontSize: 13, fontFamily: 'inherit' }}>
            Ver Sugestões
          </button>
          <div style={{ flex: 1 }}/>
          <Button variant="secondary" onClick={onClose}>Cancelar</Button>
          <button onClick={handleSave} disabled={saving} style={{ padding: '9px 20px', borderRadius: 8, background: 'linear-gradient(135deg,#FF6B6B,#FF8E53)', color: '#fff', border: 'none', cursor: saving ? 'not-allowed' : 'pointer', fontSize: 14, fontWeight: 700, fontFamily: 'inherit', opacity: saving ? 0.7 : 1 }}>
            {saving ? 'Salvando...' : (isEdit ? 'Editar Serviço' : 'Salvar Serviço')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── CategoriesModal ───────────────────────────────────────────────────────────
function CategoriesModal({ categories, onClose, onChange }) {
  const [name, setName] = useState('');
  const [color, setColor] = useState(CAT_COLORS[0]);

  function handleAdd() {
    if (!name.trim()) { window.__toast && window.__toast('Informe o nome', { tone: 'danger' }); return; }
    onChange(categories.concat([{ id: uuid(), name: name.trim(), color: color }]));
    setName('');
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,12,28,0.65)', backdropFilter: 'blur(6px)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={function(e) { e.stopPropagation(); }} style={{ width: 'min(520px,100%)', maxHeight: '88vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 16, overflow: 'hidden' }}>
        <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 14 }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, flex: 1 }}>Categorias de Serviços</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 6 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div style={{ background: 'var(--bg-elevated)', borderRadius: 12, padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ fontSize: 15, fontWeight: 700 }}>Nova Categoria</div>
            <div>
              <label style={LBL}>Nome</label>
              <input value={name} onChange={function(e) { setName(e.target.value); }} onKeyDown={function(e) { if (e.key === 'Enter') handleAdd(); }} placeholder="Ex: Design, Desenvolvimento..." style={INP}/>
            </div>
            <div>
              <label style={LBL}>Cor</label>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {CAT_COLORS.map(function(c) {
                  return (
                    <div key={c} onClick={function() { setColor(c); }} style={{
                      width: 36, height: 36, borderRadius: '50%', background: c, cursor: 'pointer',
                      outline: color === c ? '3px solid #fff' : 'none', outlineOffset: 2,
                      boxShadow: color === c ? '0 0 0 5px ' + c + '55' : 'none',
                    }}/>
                  );
                })}
              </div>
            </div>
            <button onClick={handleAdd} style={{ padding: 11, borderRadius: 10, background: 'linear-gradient(135deg,#A855F7,#EC4899)', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 700, fontFamily: 'inherit' }}>
              + Adicionar
            </button>
          </div>
          {categories.length > 0 && (
            <div>
              <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 12 }}>Categorias Existentes</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {categories.map(function(c) {
                  return (
                    <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'var(--bg-elevated)', borderRadius: 10, border: '1px solid var(--border-subtle)' }}>
                      <div style={{ width: 12, height: 12, borderRadius: '50%', background: c.color, flexShrink: 0 }}/>
                      <span style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>{c.name}</span>
                      <button onClick={function() { onChange(categories.filter(function(x) { return x.id !== c.id; })); }}
                        style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 4, borderRadius: 6 }}>
                        <Icon d={ICONS.trash} size={16}/>
                      </button>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── ServiceCard ───────────────────────────────────────────────────────────────
function ServiceCard({ service, categories, onEdit, onTogglePause, onDelete }) {
  const [menuOpen, setMenuOpen] = useState(false);
  var menuRef = useRef(null);
  var sm = STATUS_MAP[service.status] || STATUS_MAP.ativo;
  var grad = cardGradient(service, categories);
  var cat = null;
  for (var i = 0; i < categories.length; i++) {
    if (categories[i].id === service.categoryId) { cat = categories[i]; break; }
  }

  useEffect(function() {
    function handleOut(e) { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); }
    if (menuOpen) document.addEventListener('mousedown', handleOut);
    return function() { document.removeEventListener('mousedown', handleOut); };
  }, [menuOpen]);

  var pausePath = service.status === 'pausado' ? 'M5 3l14 9-14 9V3z' : 'M6 4h4v16H6zM14 4h4v16h-4z';

  return (
    <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 14, padding: 20, display: 'flex', flexDirection: 'column', gap: 12, position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: grad, flexShrink: 0 }}/>
          <Badge tone={sm.tone}>{sm.label}</Badge>
        </div>
        <div ref={menuRef} style={{ position: 'relative' }}>
          <button onClick={function() { setMenuOpen(function(o) { return !o; }); }} style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, color: 'var(--fg-muted)', cursor: 'pointer', width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon d={ICONS.more} size={16}/>
          </button>
          {menuOpen && (
            <div style={{ position: 'absolute', right: 0, top: 36, background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.2)', zIndex: 50, minWidth: 150, padding: 6 }}>
              {[
                { label: 'Editar',  fn: function() { onEdit(); setMenuOpen(false); } },
                { label: service.status === 'pausado' ? 'Reativar' : 'Pausar', fn: function() { onTogglePause(); setMenuOpen(false); } },
                { label: 'Excluir', fn: function() { onDelete(); setMenuOpen(false); }, danger: true },
              ].map(function(item) {
                return (
                  <button key={item.label} onClick={item.fn} style={{ display: 'flex', width: '100%', padding: '8px 12px', background: 'transparent', border: 'none', borderRadius: 6, cursor: 'pointer', fontSize: 13, fontFamily: 'inherit', color: item.danger ? '#EF4444' : 'var(--fg-primary)', textAlign: 'left' }}>
                    {item.label}
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <div>
        <div style={{ fontSize: 16, fontWeight: 700, lineHeight: 1.3 }}>{service.name}</div>
        {service.description && <div style={{ fontSize: 13, color: 'var(--fg-secondary)', marginTop: 4, lineHeight: 1.5 }}>{service.description}</div>}
        {cat && <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 8, padding: '3px 8px', borderRadius: 6, background: 'var(--bg-elevated)', fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)' }}><span style={{ width: 7, height: 7, borderRadius: '50%', background: cat.color }}/>{cat.name}</div>}
      </div>

      <div style={{ borderTop: '1px solid var(--border-subtle)', paddingTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 2 }}>Preço</div>
          <div style={{ fontSize: 18, fontWeight: 800, color: '#FF6B6B' }}>{fmtPrice(service.price)}</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={onTogglePause} title={service.status === 'pausado' ? 'Reativar' : 'Pausar'} style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, color: 'var(--fg-muted)', cursor: 'pointer', width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg viewBox="0 0 24 24" width={14} height={14} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
              <path d={pausePath}/>
            </svg>
          </button>
          <button onClick={onEdit} title="Editar" style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, color: 'var(--fg-muted)', cursor: 'pointer', width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon d={ICONS.pencil} size={14}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── ServiceRow ────────────────────────────────────────────────────────────────
function ServiceRow({ service, categories, onEdit, onTogglePause, onDelete, isLast }) {
  var sm = STATUS_MAP[service.status] || STATUS_MAP.ativo;
  var cat = null;
  for (var i = 0; i < categories.length; i++) {
    if (categories[i].id === service.categoryId) { cat = categories[i]; break; }
  }
  var grad = cardGradient(service, categories);
  var pausePath = service.status === 'pausado' ? 'M5 3l14 9-14 9V3z' : 'M6 4h4v16H6zM14 4h4v16h-4z';
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr auto', alignItems: 'center', gap: 12, padding: '14px 18px', borderBottom: isLast ? 'none' : '1px solid var(--border-subtle)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
        <div style={{ width: 34, height: 34, borderRadius: 8, background: grad, flexShrink: 0 }}/>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{service.name}</div>
          {service.description && <div style={{ fontSize: 12, color: 'var(--fg-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{service.description}</div>}
        </div>
      </div>
      <div>{cat ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: cat.color }}/>{cat.name}</span> : <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>—</span>}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: '#FF6B6B' }}>{fmtPrice(service.price)}</div>
      <div><Badge tone={sm.tone}>{sm.label}</Badge></div>
      <div style={{ display: 'flex', gap: 6 }}>
        <button onClick={onTogglePause} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 6, borderRadius: 6 }}>
          <svg viewBox="0 0 24 24" width={14} height={14} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
            <path d={pausePath}/>
          </svg>
        </button>
        <button onClick={onEdit} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 6, borderRadius: 6 }}>
          <Icon d={ICONS.pencil} size={14}/>
        </button>
        <button onClick={onDelete} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 6, borderRadius: 6 }}>
          <Icon d={ICONS.trash} size={14}/>
        </button>
      </div>
    </div>
  );
}

// ─── Services (main) ───────────────────────────────────────────────────────────
function Services({ onNav }) {
  const [services,    setServices]    = useState([]);
  const [categories,  setCategories]  = useState([]);
  const [userId,      setUserId]      = useState(null);
  const [loading,     setLoading]     = useState(true);
  const [viewMode,    setViewMode]    = useState('grid');
  const [q,           setQ]           = useState('');
  const [showFilters, setShowFilters] = useState(false);
  const [filters,     setFilters]     = useState({ status: 'todos', recorrente: 'todos', visibilidade: [] });
  const [sortBy,      setSortBy]      = useState('recent');
  const [modal,       setModal]       = useState(null);
  const [editTarget,  setEditTarget]  = useState(null);

  useEffect(function() {
    sb.auth.getUser().then(function(res) {
      var user = res && res.data && res.data.user;
      if (user) {
        setUserId(user.id);
        setServices(loadServices(user.id));
        setCategories(loadCategories(user.id));
      }
      setLoading(false);
    }).catch(function() { setLoading(false); });
  }, []);

  function persistServices(arr) { setServices(arr); if (userId) saveServices(userId, arr); }
  function persistCategories(arr) { setCategories(arr); if (userId) saveCategories(userId, arr); }

  function handleSave(obj) {
    var updated = editTarget ? services.map(function(s) { return s.id === obj.id ? obj : s; }) : [obj].concat(services);
    persistServices(updated);
    window.__toast && window.__toast(editTarget ? 'Serviço atualizado' : 'Serviço criado', { tone: 'success' });
    setModal(null); setEditTarget(null);
    return Promise.resolve();
  }

  function handleTogglePause(service) {
    var next = service.status === 'pausado' ? 'ativo' : 'pausado';
    persistServices(services.map(function(s) { return s.id === service.id ? Object.assign({}, s, { status: next }) : s; }));
    window.__toast && window.__toast(next === 'pausado' ? 'Serviço pausado' : 'Serviço reativado', { tone: 'info' });
  }

  function handleDelete(service) {
    if (!window.confirm('Excluir "' + service.name + '"? Esta ação não pode ser desfeita.')) return;
    persistServices(services.filter(function(s) { return s.id !== service.id; }));
    window.__toast && window.__toast('Serviço excluído', { tone: 'success' });
  }

  var visible = services.filter(function(s) {
    if (q && !s.name.toLowerCase().includes(q.toLowerCase()) && !(s.description || '').toLowerCase().includes(q.toLowerCase())) return false;
    if (filters.status !== 'todos' && s.status !== filters.status) return false;
    if (filters.recorrente !== 'todos' && String(s.recorrente) !== filters.recorrente) return false;
    if (filters.visibilidade.length && !filters.visibilidade.some(function(v) { return s[v]; })) return false;
    return true;
  }).sort(function(a, b) {
    if (sortBy === 'price_desc') return (b.price || 0) - (a.price || 0);
    if (sortBy === 'price_asc')  return (a.price || 0) - (b.price || 0);
    if (sortBy === 'az')         return a.name.localeCompare(b.name);
    if (sortBy === 'oldest')     return new Date(a.createdAt) - new Date(b.createdAt);
    return new Date(b.createdAt) - new Date(a.createdAt);
  });

  var totalAtivo   = services.filter(function(s) { return s.status === 'ativo'; }).length;
  var totalPausado = services.filter(function(s) { return s.status === 'pausado'; }).length;
  var recorrenteCt = services.filter(function(s) { return s.recorrente; }).length;

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>Carregando serviços…</div>;

  return (
    <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column', gap: 18 }}>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
        <Button variant="secondary" onClick={function() { setModal('categories'); }}>Gerenciar Categorias</Button>
        <Button variant="ghost" onClick={function() { onNav && onNav('budgets'); }}>Novo Orçamento</Button>
        <button onClick={function() { setEditTarget(null); setModal('new'); }} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 18px', borderRadius: 10, background: 'linear-gradient(135deg,#FF6B6B,#FF8E53)', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 700, fontFamily: 'inherit' }}>
          <Icon d={ICONS.plus} size={14}/> Novo Serviço
        </button>
      </div>

      <div style={{ display: 'flex', flexDirection: 'row', gap: 14 }}>
        {[
          { l: 'Total de Serviços', v: services.length, d: 'serviços cadastrados' },
          { l: 'Ativos',            v: totalAtivo,      d: 'em andamento' },
          { l: 'Pausados',          v: totalPausado,    d: 'temporariamente inativos' },
          { l: 'Recorrentes',       v: recorrenteCt,    d: 'cobranças recorrentes' },
        ].map(function(item) {
          return (
            <div key={item.l} style={{ flex: 1, background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 14, boxShadow: 'var(--shadow-2)', padding: 18 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-muted)' }}>{item.l}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700, marginTop: 8, letterSpacing: '-0.02em' }}>{item.v}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{item.d}</div>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ flex: 1, position: 'relative' }}>
          <Icon d={ICONS.search} size={14} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-muted)' }}/>
          <input value={q} onChange={function(e) { setQ(e.target.value); }} placeholder="Buscar serviços..." style={Object.assign({}, INP, { paddingLeft: 38, background: 'var(--bg-elevated)' })}/>
        </div>
        <button onClick={function() { setShowFilters(function(f) { return !f; }); }} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 16px', borderRadius: 10, border: '1px solid var(--border-subtle)', background: showFilters ? 'var(--primary-soft)' : 'var(--bg-elevated)', color: showFilters ? 'var(--geek-blue-200)' : 'var(--fg-secondary)', cursor: 'pointer', fontSize: 14, fontWeight: 600, fontFamily: 'inherit' }}>
          <Icon d={ICONS.filter} size={14}/> Filtros
        </button>
        <div style={{ display: 'flex', border: '1px solid var(--border-subtle)', borderRadius: 8, overflow: 'hidden' }}>
          {[['grid', ICONS.grid], ['list', ICONS.list]].map(function(pair) {
            return (
              <button key={pair[0]} onClick={function() { setViewMode(pair[0]); }} style={{ padding: '8px 12px', border: 'none', cursor: 'pointer', background: viewMode === pair[0] ? 'var(--primary-soft)' : 'var(--bg-elevated)', color: viewMode === pair[0] ? 'var(--geek-blue-200)' : 'var(--fg-muted)' }}>
                <Icon d={pair[1]} size={16}/>
              </button>
            );
          })}
        </div>
      </div>

      {showFilters && (
        <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 12, padding: 20, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 24 }}>
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 10 }}>Status</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {['todos', 'ativo', 'pausado', 'arquivado'].map(function(v) {
                var active = filters.status === v;
                return <button key={v} onClick={function() { setFilters(function(f) { return Object.assign({}, f, { status: v }); }); }} style={{ padding: '7px 14px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 13, fontFamily: 'inherit', fontWeight: 600, background: active ? '#FF6B6B' : 'var(--bg-elevated)', color: active ? '#fff' : 'var(--fg-secondary)' }}>{v.charAt(0).toUpperCase() + v.slice(1)}</button>;
              })}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 10 }}>Recorrente</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {[['todos', 'Todos'], ['true', 'Sim'], ['false', 'Não']].map(function(pair) {
                var active = filters.recorrente === pair[0];
                return <button key={pair[0]} onClick={function() { setFilters(function(f) { return Object.assign({}, f, { recorrente: pair[0] }); }); }} style={{ padding: '7px 14px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 13, fontFamily: 'inherit', fontWeight: 600, background: active ? '#FF6B6B' : 'var(--bg-elevated)', color: active ? '#fff' : 'var(--fg-secondary)' }}>{pair[1]}</button>;
              })}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 10 }}>Visibilidade</div>
            {[['exibirPaginaPublica', 'Página pública'], ['exibirFormularioLeads', 'Formulário de leads']].map(function(pair) {
              var checked = filters.visibilidade.includes(pair[0]);
              return (
                <label key={pair[0]} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: 'var(--fg-secondary)', padding: '6px 0' }}>
                  <input type="checkbox" checked={checked} onChange={function() { setFilters(function(f) { var vis = checked ? f.visibilidade.filter(function(x) { return x !== pair[0]; }) : f.visibilidade.concat([pair[0]]); return Object.assign({}, f, { visibilidade: vis }); }); }} style={{ accentColor: '#FF6B6B', width: 14, height: 14 }}/>
                  {pair[1]}
                </label>
              );
            })}
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 10 }}>Ordenar por</div>
            <select value={sortBy} onChange={function(e) { setSortBy(e.target.value); }} style={Object.assign({}, INP, { cursor: 'pointer' })}>
              <option value="recent">Mais recente</option>
              <option value="oldest">Mais antigo</option>
              <option value="price_desc">Maior preço</option>
              <option value="price_asc">Menor preço</option>
              <option value="az">A–Z</option>
            </select>
          </div>
        </div>
      )}

      {visible.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--fg-muted)', fontSize: 14 }}>
          {services.length === 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 64, height: 64, borderRadius: 16, background: 'var(--bg-elevated)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg viewBox="0 0 24 24" width={28} height={28} fill="none" stroke="var(--fg-muted)" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
                </svg>
              </div>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--fg-primary)', marginBottom: 4 }}>Nenhum serviço cadastrado</div>
                <div style={{ fontSize: 14 }}>Adicione os serviços que você oferece e seus preços.</div>
              </div>
              <button onClick={function() { setEditTarget(null); setModal('new'); }} style={{ padding: '10px 22px', borderRadius: 10, background: 'linear-gradient(135deg,#FF6B6B,#FF8E53)', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 700, fontFamily: 'inherit' }}>
                + Adicionar primeiro serviço
              </button>
            </div>
          ) : 'Nenhum serviço encontrado com esses filtros.'}
        </div>
      ) : viewMode === 'grid' ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 16 }}>
          {visible.map(function(s) {
            return <ServiceCard key={s.id} service={s} categories={categories}
              onEdit={function() { setEditTarget(s); setModal('edit'); }}
              onTogglePause={function() { handleTogglePause(s); }}
              onDelete={function() { handleDelete(s); }}/>;
          })}
        </div>
      ) : (
        <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr auto', gap: 12, padding: '10px 18px', background: 'var(--bg-elevated)', borderBottom: '1px solid var(--border-subtle)' }}>
            {['Serviço', 'Categoria', 'Preço', 'Status', ''].map(function(h) { return <span key={h} style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{h}</span>; })}
          </div>
          {visible.map(function(s, idx) {
            return <ServiceRow key={s.id} service={s} categories={categories} isLast={idx === visible.length - 1}
              onEdit={function() { setEditTarget(s); setModal('edit'); }}
              onTogglePause={function() { handleTogglePause(s); }}
              onDelete={function() { handleDelete(s); }}/>;
          })}
        </div>
      )}

      {(modal === 'new' || modal === 'edit') && (
        <ServiceModal service={editTarget} categories={categories} onClose={function() { setModal(null); setEditTarget(null); }} onSave={handleSave}/>
      )}
      {modal === 'categories' && (
        <CategoriesModal categories={categories} onClose={function() { setModal(null); }} onChange={function(arr) { persistCategories(arr); }}/>
      )}
    </div>
  );
}

console.log('[Services.jsx] v9 end — registering window.Services');
window.Services = Services;
window.dispatchEvent(new CustomEvent('services-ready'));
