
// ============================================================
// JuFlow — Configurações
// ============================================================
const { useState: useStCF } = React;
const UCF = window.JFUtils;

const Configuracoes = ({ addToast }) => {
  const [tab, setTab] = useStCF('empresa');
  const [empresa, setEmpresa] = useStCF({
    nome: 'Studio JuFlow', cnpj: '12.345.678/0001-90',
    email: 'contato@juflow.com', telefone: '(11) 3000-0000',
    endereco: 'Rua das Flores, 123, Jardins, São Paulo - SP',
    descricao: 'Estúdio de bem-estar e estética com foco em resultados e experiência premium.',
  });
  const [horarios, setHorarios] = useStCF({
    0: { open:false, start:'09:00', end:'17:00' },
    1: { open:true,  start:'08:00', end:'19:00' },
    2: { open:true,  start:'08:00', end:'19:00' },
    3: { open:true,  start:'08:00', end:'19:00' },
    4: { open:true,  start:'08:00', end:'19:00' },
    5: { open:true,  start:'08:00', end:'19:00' },
    6: { open:true,  start:'09:00', end:'17:00' },
  });
  const [cores, setCores] = useStCF({ primary:'#0A1F44', accent:'#FF6B35' });
  const [lembretes, setLembretes] = useStCF({ whatsapp24h:true, whatsapp1h:false, email24h:true });
  const [categories, setCategories] = useStCF(['Massagem','Estética','Fisioterapia','Nutrição','Fitness','Beleza','Podologia']);
  const [catModal, setCatModal] = useStCF({ open:false, mode:'create', original:'', value:'' });
  const [catConfirm, setCatConfirm] = useStCF({ open:false, name:'' });

  const DAYS = ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'];
  const USERS = [
    { id:1, name:'Admin Demo', email:'demo@juflow.com', role:'Admin', status:'active' },
    { id:2, name:'Dra. Ana Beatriz', email:'ana@clinica.com', role:'Profissional', status:'active' },
    { id:3, name:'Carla Mendes', email:'carla@clinica.com', role:'Profissional', status:'active' },
    { id:4, name:'Recepcionista', email:'recepcao@clinica.com', role:'Recepção', status:'active' },
  ];

  const openCreateCat = () => setCatModal({ open:true, mode:'create', original:'', value:'' });
  const openEditCat = (name) => setCatModal({ open:true, mode:'edit', original:name, value:name });
  const closeCatModal = () => setCatModal(m => ({ ...m, open:false }));
  const saveCat = () => {
    const v = catModal.value.trim();
    if (!v) { addToast('Informe um nome para a categoria.', 'warning'); return; }
    if (catModal.mode === 'create') {
      if (categories.some(c => c.toLowerCase() === v.toLowerCase())) {
        addToast('Já existe uma categoria com esse nome.', 'warning'); return;
      }
      setCategories(cs => [...cs, v]);
      addToast(`Categoria "${v}" adicionada!`, 'success');
    } else {
      if (v !== catModal.original && categories.some(c => c.toLowerCase() === v.toLowerCase())) {
        addToast('Já existe uma categoria com esse nome.', 'warning'); return;
      }
      setCategories(cs => cs.map(c => c === catModal.original ? v : c));
      addToast(`Categoria atualizada para "${v}".`, 'success');
    }
    closeCatModal();
  };
  const askDeleteCat = (name) => setCatConfirm({ open:true, name });
  const confirmDeleteCat = () => {
    setCategories(cs => cs.filter(c => c !== catConfirm.name));
    addToast(`Categoria "${catConfirm.name}" excluída.`, 'success');
  };

  const setHorario = (day, key, val) => setHorarios(h => ({ ...h, [day]: { ...h[day], [key]: val } }));
  const setEmpresaField = (k, v) => setEmpresa(e => ({ ...e, [k]: v }));

  const handleSave = () => addToast('Configurações salvas com sucesso!', 'success');

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      <Tabs
        tabs={[
          { id:'empresa',    label:'Empresa',              icon:'Building2' },
          { id:'horarios',   label:'Horário de Funcionamento', icon:'Clock' },
          { id:'usuarios',   label:'Usuários',             icon:'Users' },
          { id:'aparencia',  label:'Aparência',            icon:'Palette' },
          { id:'lembretes',  label:'Lembretes Automáticos', icon:'Bell' },
          { id:'categorias', label:'Categorias',           icon:'Tag' },
        ]}
        activeTab={tab}
        onTabChange={setTab}
      />

      {tab === 'empresa' && (
        <div style={{ background:'#fff', borderRadius:14, padding:24, boxShadow:'0 2px 8px rgba(10,31,68,.06)', maxWidth:680 }}>
          <h3 style={{ fontSize:15, fontWeight:700, color:'#0A1F44', margin:'0 0 20px', display:'flex', alignItems:'center', gap:8 }}>
            <Icon name="Building2" size={16} color="#FF6B35" /> Dados da Empresa
          </h3>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <Input label="Nome da Empresa" value={empresa.nome} onChange={v=>setEmpresaField('nome',v)} icon="Building2" style={{ gridColumn:'1/-1' }} />
            <Input label="CNPJ" value={empresa.cnpj} onChange={v=>setEmpresaField('cnpj',v)} icon="FileText" />
            <Input label="Telefone" value={empresa.telefone} onChange={v=>setEmpresaField('telefone',v)} icon="Phone" />
            <Input label="E-mail" type="email" value={empresa.email} onChange={v=>setEmpresaField('email',v)} icon="Mail" style={{ gridColumn:'1/-1' }} />
            <Input label="Endereço" value={empresa.endereco} onChange={v=>setEmpresaField('endereco',v)} icon="MapPin" style={{ gridColumn:'1/-1' }} />
            <Textarea label="Descrição" value={empresa.descricao} onChange={v=>setEmpresaField('descricao',v)} rows={3} style={{ gridColumn:'1/-1' }} />
          </div>

          {/* Logo placeholder */}
          <div style={{ marginTop:20 }}>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:8 }}>Logo da Empresa</label>
            <div style={{
              width:120, height:120, borderRadius:14, border:'2px dashed #D1D5DB',
              display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
              gap:6, cursor:'pointer', transition:'all .15s',
              background:'#F9FAFB',
            }}
              onMouseEnter={e=>{ e.currentTarget.style.borderColor='#FF6B35'; e.currentTarget.style.background='#FFF0EA'; }}
              onMouseLeave={e=>{ e.currentTarget.style.borderColor='#D1D5DB'; e.currentTarget.style.background='#F9FAFB'; }}
            >
              <Icon name="Upload" size={24} color="#9CA3AF" />
              <span style={{ fontSize:11, color:'#9CA3AF' }}>Enviar logo</span>
            </div>
          </div>

          <Button variant="primary" icon="Save" style={{ marginTop:20 }} onClick={handleSave}>Salvar Dados</Button>
        </div>
      )}

      {tab === 'horarios' && (
        <div style={{ background:'#fff', borderRadius:14, padding:24, boxShadow:'0 2px 8px rgba(10,31,68,.06)', maxWidth:560 }}>
          <h3 style={{ fontSize:15, fontWeight:700, color:'#0A1F44', margin:'0 0 20px' }}>Horário de Funcionamento</h3>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {DAYS.map((day, i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:14, padding:'10px 14px', borderRadius:10, background:'#F9FAFB', border:'1px solid #E2E8F0' }}>
                <div style={{ width:130 }}>
                  <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer' }}>
                    <div
                      onClick={() => setHorario(i,'open',!horarios[i].open)}
                      style={{ width:38, height:20, borderRadius:10, background:horarios[i].open?'#FF6B35':'#D1D5DB', position:'relative', cursor:'pointer', transition:'background .2s', flexShrink:0 }}
                    >
                      <div style={{ position:'absolute', top:2, left:horarios[i].open?20:2, width:16, height:16, borderRadius:'50%', background:'#fff', transition:'left .2s', boxShadow:'0 1px 3px rgba(0,0,0,.2)' }} />
                    </div>
                    <span style={{ fontSize:13, fontWeight:horarios[i].open?700:400, color:horarios[i].open?'#0A1F44':'#9CA3AF' }}>{day}</span>
                  </label>
                </div>
                {horarios[i].open ? (
                  <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <input type="time" value={horarios[i].start} onChange={e=>setHorario(i,'start',e.target.value)} style={{ padding:'5px 8px', borderRadius:6, border:'1px solid #E2E8F0', fontSize:12, color:'#0A1F44', outline:'none' }} />
                    <span style={{ fontSize:12, color:'#9CA3AF' }}>até</span>
                    <input type="time" value={horarios[i].end} onChange={e=>setHorario(i,'end',e.target.value)} style={{ padding:'5px 8px', borderRadius:6, border:'1px solid #E2E8F0', fontSize:12, color:'#0A1F44', outline:'none' }} />
                  </div>
                ) : (
                  <span style={{ fontSize:12, color:'#9CA3AF', fontStyle:'italic' }}>Fechado</span>
                )}
              </div>
            ))}
          </div>
          <Button variant="primary" icon="Save" style={{ marginTop:20 }} onClick={handleSave}>Salvar Horários</Button>
        </div>
      )}

      {tab === 'usuarios' && (
        <div style={{ background:'#fff', borderRadius:14, overflow:'hidden', boxShadow:'0 2px 8px rgba(10,31,68,.06)', maxWidth:700 }}>
          <div style={{ padding:'14px 18px', borderBottom:'1px solid #E2E8F0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <h3 style={{ margin:0, fontSize:15, fontWeight:700, color:'#0A1F44' }}>Usuários do Sistema</h3>
            <Button size="sm" variant="primary" icon="UserPlus" onClick={()=>addToast('Convite enviado!','success')}>Convidar usuário</Button>
          </div>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead>
              <tr style={{ background:'#F9FAFB' }}>
                {['Usuário','E-mail','Perfil','Status','Ações'].map(h=>(
                  <th key={h} style={{ padding:'11px 16px', fontSize:11, fontWeight:700, color:'#6B7280', textAlign:'left', textTransform:'uppercase', letterSpacing:.5 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {USERS.map((u,i) => (
                <tr key={u.id} style={{ borderTop:'1px solid #F0F4F8' }}>
                  <td style={{ padding:'12px 16px' }}><div style={{ display:'flex', alignItems:'center', gap:8 }}><Avatar name={u.name} color="#0A1F44" size={32} /><span style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{u.name}</span></div></td>
                  <td style={{ padding:'12px 16px', fontSize:12, color:'#6B7280' }}>{u.email}</td>
                  <td style={{ padding:'12px 16px' }}>
                    <span style={{
                      padding:'3px 10px', borderRadius:20, fontSize:11, fontWeight:700,
                      background: u.role==='Admin'?'#FFF0EA': u.role==='Profissional'?'#EFF6FF':'#F0FDF4',
                      color: u.role==='Admin'?'#FF6B35': u.role==='Profissional'?'#2563EB':'#059669',
                    }}>{u.role}</span>
                  </td>
                  <td style={{ padding:'12px 16px' }}><Badge status="active" /></td>
                  <td style={{ padding:'12px 16px' }}>
                    <Button size="sm" variant="ghost" icon="Edit2" onClick={()=>addToast('Edição em breve!','info')}>Editar</Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'aparencia' && (
        <div style={{ background:'#fff', borderRadius:14, padding:24, boxShadow:'0 2px 8px rgba(10,31,68,.06)', maxWidth:480 }}>
          <h3 style={{ fontSize:15, fontWeight:700, color:'#0A1F44', margin:'0 0 20px' }}>Personalização Visual</h3>
          <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
            {[
              { label:'Cor Primária', key:'primary', presets:['#0A1F44','#1E3A5F','#064E3B','#312E81','#7C2D12'] },
              { label:'Cor de Acento', key:'accent', presets:['#FF6B35','#F59E0B','#10B981','#3B82F6','#8B5CF6'] },
            ].map(({label,key,presets}) => (
              <div key={key}>
                <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:10 }}>{label}</label>
                <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                  {presets.map(c => (
                    <button key={c} onClick={() => setCores(co=>({...co,[key]:c}))} style={{
                      width:32, height:32, borderRadius:8, background:c, border:`3px solid ${cores[key]===c?'#0A1F44':'transparent'}`,
                      cursor:'pointer', boxShadow:'0 2px 6px rgba(0,0,0,.2)', transition:'transform .15s',
                    }}
                      onMouseEnter={e=>e.currentTarget.style.transform='scale(1.15)'}
                      onMouseLeave={e=>e.currentTarget.style.transform='scale(1)'}
                    />
                  ))}
                  <input type="color" value={cores[key]} onChange={e=>setCores(co=>({...co,[key]:e.target.value}))} style={{ width:32, height:32, borderRadius:8, border:'1px solid #E2E8F0', cursor:'pointer', padding:2 }} />
                </div>
              </div>
            ))}

            {/* Preview */}
            <div style={{ background:'#F9FAFB', borderRadius:12, padding:14, marginTop:4 }}>
              <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5, marginBottom:10 }}>Preview</div>
              <div style={{ display:'flex', gap:10, alignItems:'center', flexWrap:'wrap' }}>
                <div style={{ background:cores.primary, color:'#fff', padding:'8px 16px', borderRadius:8, fontSize:13, fontWeight:600 }}>Botão Primário</div>
                <div style={{ background:cores.accent, color:'#fff', padding:'8px 16px', borderRadius:8, fontSize:13, fontWeight:600 }}>Botão de Acento</div>
                <div style={{ color:cores.primary, fontSize:14, fontWeight:800 }}>Texto Primário</div>
                <div style={{ color:cores.accent, fontSize:14, fontWeight:700 }}>Link de Destaque</div>
              </div>
            </div>
          </div>
          <Button variant="primary" icon="Save" style={{ marginTop:20 }} onClick={handleSave}>Aplicar Aparência</Button>
        </div>
      )}

      {tab === 'lembretes' && (
        <div style={{ background:'#fff', borderRadius:14, padding:24, boxShadow:'0 2px 8px rgba(10,31,68,.06)', maxWidth:520 }}>
          <h3 style={{ fontSize:15, fontWeight:700, color:'#0A1F44', margin:'0 0 20px' }}>Lembretes Automáticos</h3>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {[
              { key:'whatsapp24h', label:'WhatsApp — 24h antes', desc:'Enviar mensagem de lembrete um dia antes do atendimento', icon:'MessageCircle', color:'#25D366' },
              { key:'whatsapp1h',  label:'WhatsApp — 1h antes',  desc:'Enviar mensagem de lembrete uma hora antes do atendimento', icon:'MessageCircle', color:'#25D366' },
              { key:'email24h',    label:'E-mail — 24h antes',   desc:'Enviar e-mail de confirmação um dia antes do atendimento', icon:'Mail', color:'#0891B2' },
            ].map(item => (
              <div key={item.key} style={{ display:'flex', alignItems:'center', gap:14, padding:'14px 16px', borderRadius:12, background:'#F9FAFB', border:'1px solid #E2E8F0' }}>
                <div style={{ width:36,height:36,borderRadius:10,background:UCF.hexToRgba(item.color,.12),display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 }}>
                  <Icon name={item.icon} size={18} color={item.color} />
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{item.label}</div>
                  <div style={{ fontSize:11, color:'#9CA3AF' }}>{item.desc}</div>
                </div>
                <div onClick={() => setLembretes(l=>({...l,[item.key]:!l[item.key]}))}
                  style={{ width:42,height:22,borderRadius:11,background:lembretes[item.key]?'#FF6B35':'#D1D5DB',position:'relative',cursor:'pointer',transition:'background .2s',flexShrink:0 }}
                >
                  <div style={{ position:'absolute',top:3,left:lembretes[item.key]?22:3,width:16,height:16,borderRadius:'50%',background:'#fff',transition:'left .2s',boxShadow:'0 1px 3px rgba(0,0,0,.2)' }} />
                </div>
              </div>
            ))}
          </div>
          <Button variant="primary" icon="Save" style={{ marginTop:20 }} onClick={handleSave}>Salvar Configurações</Button>
        </div>
      )}

      {tab === 'categorias' && (
        <div style={{ background:'#fff', borderRadius:14, padding:24, boxShadow:'0 2px 8px rgba(10,31,68,.06)', maxWidth:460 }}>
          <h3 style={{ fontSize:15, fontWeight:700, color:'#0A1F44', margin:'0 0 16px' }}>Categorias de Serviço</h3>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {categories.map(cat => (
              <div key={cat} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 14px', borderRadius:10, background:'#F9FAFB', border:'1px solid #E2E8F0' }}>
                <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                  <Icon name="Tag" size={14} color="#FF6B35" />
                  <span style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{cat}</span>
                  <span style={{ fontSize:11, color:'#9CA3AF' }}>({window.JF.SERVICES.filter(s=>s.category===cat).length} serviços)</span>
                </div>
                <div style={{ display:'flex', gap:6 }}>
                  <button title="Editar" onClick={()=>openEditCat(cat)} style={{ width:30,height:30,borderRadius:8,border:'1px solid #E2E8F0',background:'#fff',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',transition:'all .15s' }}
                    onMouseEnter={e=>{ e.currentTarget.style.background='#EFF6FF'; e.currentTarget.style.borderColor='#3B82F6'; }}
                    onMouseLeave={e=>{ e.currentTarget.style.background='#fff'; e.currentTarget.style.borderColor='#E2E8F0'; }}
                  ><Icon name="Edit2" size={14} color="#3B82F6" /></button>
                  <button title="Excluir" onClick={()=>askDeleteCat(cat)} style={{ width:30,height:30,borderRadius:8,border:'1px solid #E2E8F0',background:'#fff',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',transition:'all .15s' }}
                    onMouseEnter={e=>{ e.currentTarget.style.background='#FEF2F2'; e.currentTarget.style.borderColor='#EF4444'; }}
                    onMouseLeave={e=>{ e.currentTarget.style.background='#fff'; e.currentTarget.style.borderColor='#E2E8F0'; }}
                  ><Icon name="Trash2" size={14} color="#EF4444" /></button>
                </div>
              </div>
            ))}
            {categories.length === 0 && (
              <div style={{ padding:'18px 14px', borderRadius:10, background:'#F9FAFB', border:'1px dashed #E2E8F0', textAlign:'center', fontSize:12, color:'#9CA3AF' }}>
                Nenhuma categoria cadastrada.
              </div>
            )}
          </div>
          <Button variant="primary" icon="Plus" style={{ marginTop:14 }} onClick={openCreateCat}>Nova Categoria</Button>

          <Modal
            open={catModal.open}
            onClose={closeCatModal}
            title={catModal.mode === 'create' ? 'Nova Categoria' : 'Editar Categoria'}
            width={420}
            footer={<>
              <Button variant="secondary" onClick={closeCatModal}>Cancelar</Button>
              <Button variant="primary" icon="Save" onClick={saveCat}>Salvar</Button>
            </>}
          >
            <Input
              label="Nome da categoria"
              value={catModal.value}
              onChange={v => setCatModal(m => ({ ...m, value: v }))}
              icon="Tag"
              autoFocus
              onKeyDown={e => { if (e.key === 'Enter') saveCat(); }}
            />
          </Modal>

          <ConfirmDialog
            open={catConfirm.open}
            onClose={() => setCatConfirm(c => ({ ...c, open:false }))}
            onConfirm={confirmDeleteCat}
            title="Excluir categoria"
            message={`Tem certeza que deseja excluir a categoria "${catConfirm.name}"? Os serviços associados não serão removidos, mas ficarão sem categoria.`}
            confirmLabel="Excluir"
            danger
          />
        </div>
      )}
    </div>
  );
};

Object.assign(window, { Configuracoes });
