import React, { useState, useRef, useEffect } from 'react';
import { useAuth } from '../../context/AuthContext';
import { notificationService } from '../../services/notificationService';

function loadBranding() {
  try { const s = localStorage.getItem('arpm_branding'); return s ? JSON.parse(s) : {}; }
  catch { return {}; }
}
function saveBranding(data) {
  localStorage.setItem('arpm_branding', JSON.stringify(data));
  window.dispatchEvent(new Event('arpm_branding_updated'));
}

const INITIAL = {
  // Empresa
  companyName: 'AR Electronics S.A.S.',
  tradeName: '',
  taxId: '900.123.456-7',
  taxIdType: 'NIT',
  legalRep: '',
  industry: 'CONSTRUCCIÃ“N',
  companyType: 'SAS',
  website: '',
  logo: null,

  // DirecciÃ³n
  address: 'Calle 72 # 10-34, Piso 5',
  city: 'BogotÃ¡',
  state: 'Cundinamarca',
  country: 'Colombia',
  zip: '110221',

  // Contacto
  phone: '+57 601 555 0100',
  mobile: '+57 310 555 0200',
  email: 'contacto@arelectronics.com',
  emailFinance: 'finanzas@arelectronics.com',

  // Moneda & fiscal
  currency: 'COP',
  currencySymbol: '$',
  taxRate: 19,
  taxName: 'IVA',
  fiscalYearStart: '01-01',
  dateFormat: 'DD/MM/YYYY',

  // Proyecto defaults
  defaultHoursPerDay: 8,
  defaultDaysPerWeek: 5,
  projectCodePrefix: 'PRY',
  otCodePrefix: 'OT',
  rfqCodePrefix: 'RFQ',

  // Notificaciones
  notifyOverdueTask: true,
  notifyBudgetAlert: true,
  notifyBudgetThreshold: 80,
  notifyNewOT: false,

  // IA
  aiProvider:    'ollama',
  aiLocalUrl:    'http://localhost:11434',
  aiLocalModel:  'llama3',
  claudeApiKey:  '',
  claudeModel:   'claude-sonnet-4-6',
  openaiApiKey:  '',
  openaiModel:   'gpt-4o',
  aiSubtasks:    true,
  aiEstimate:    true,
  aiPerformance: true,
  aiOverrun:     true,

  // Licencia
  licenseKey: 'ARPM-2026-ENT-X7K9-M3P2-Q8R1',
  licenseEmail: 'contacto@arelectronics.com',
  licenseCompany: 'AR Electronics S.A.S.',

  // Acceso admin
  adminEmail: 'admin@arpm.com',
  adminPassword: 'Admin123!',
  adminPasswordConfirm: '',
};

const TABS = [
  { key:'empresa',    label:'Empresa',         icon:'M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4' },
  { key:'contacto',   label:'Contacto',        icon:'M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z' },
  { key:'fiscal',     label:'Fiscal & Moneda', icon:'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
  { key:'proyectos',  label:'Proyectos',       icon:'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' },
  { key:'notif',      label:'Notificaciones',  icon:'M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9' },
  { key:'licencia',   label:'Licencia',        icon:'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z' },
  { key:'ia',         label:'Inteligencia IA', icon:'M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z' },
  { key:'mensajeria', label:'MensajerÃ­a',      icon:'M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z' },
];

function Field({ label, hint, children }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1.5">{label}</label>
      {children}
      {hint && <p className="mt-1 text-xs text-slate-400 dark:text-gray-600">{hint}</p>}
    </div>
  );
}

function Input({ value, onChange, type='text', placeholder='', mono=false, disabled=false, ...rest }) {
  return (
    <input type={type} value={value} onChange={onChange} placeholder={placeholder} disabled={disabled} {...rest}
      className={`w-full text-sm border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 ${mono ? 'font-mono' : ''} ${disabled ? 'bg-slate-100 dark:bg-surface-800 border-slate-200 dark:border-surface-700 text-slate-400 dark:text-gray-600 cursor-not-allowed' : 'bg-slate-50 dark:bg-surface-700 border-slate-200 dark:border-surface-600 text-slate-800 dark:text-gray-200 placeholder-slate-300 dark:placeholder-gray-600'}`}/>
  );
}

function Select({ value, onChange, options, disabled=false }) {
  return (
    <select value={value} onChange={onChange} disabled={disabled}
      className={`w-full text-sm border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 ${disabled ? 'bg-slate-100 dark:bg-surface-800 border-slate-200 dark:border-surface-700 text-slate-400 dark:text-gray-600 cursor-not-allowed' : 'bg-slate-50 dark:bg-surface-700 border-slate-200 dark:border-surface-600 text-slate-800 dark:text-gray-200'}`}>
      {options.map(o => <option key={o.value ?? o} value={o.value ?? o}>{o.label ?? o}</option>)}
    </select>
  );
}

function AdminBanner() {
  return (
    <div className="flex items-center gap-2 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 rounded-xl px-4 py-3 mb-4">
      <svg className="w-4 h-4 text-amber-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
      <p className="text-xs text-amber-700 dark:text-amber-400">Solo el administrador puede modificar esta secciÃ³n.</p>
    </div>
  );
}

function Toggle({ checked, onChange, label }) {
  return (
    <label className="flex items-center gap-3 cursor-pointer">
      <button type="button" onClick={()=>onChange(!checked)}
        className={`relative w-10 h-5 rounded-full transition-colors ${checked ? 'bg-blue-600' : 'bg-slate-200 dark:bg-surface-600'}`}>
        <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${checked ? 'translate-x-5' : ''}`}/>
      </button>
      <span className="text-sm text-slate-700 dark:text-gray-300">{label}</span>
    </label>
  );
}

function SectionTitle({ children }) {
  return <h3 className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-widest pt-2 pb-1 border-b border-slate-100 dark:border-surface-700 mb-4">{children}</h3>;
}

export default function SettingsPage() {
  const { user } = useAuth();
  const isAdmin = user?.role === 'SUPER_ADMIN';
  const [tab, setTab]       = useState('empresa');
  const [form, setForm]     = useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('arpm_settings') || '{}');
      return { ...INITIAL, ...saved, adminPasswordConfirm: '' };
    } catch { return INITIAL; }
  });
  const [pwdError, setPwdError] = useState('');
  const [saved, setSaved]   = useState(false);
  const [branding, setBranding] = useState(loadBranding);
  const [msgConfig, setMsgConfig] = useState(() => {
    try { return JSON.parse(localStorage.getItem('arpm_messaging') || '{}'); }
    catch { return {}; }
  });
  const logoRef = useRef();

  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setSaved(false); };
  const setMsg = (k, v) => setMsgConfig(m => ({ ...m, [k]: v }));

  const handleSave = () => {
    if (form.adminPasswordConfirm && form.adminPassword !== form.adminPasswordConfirm) {
      setPwdError('Las contraseÃ±as no coinciden');
      setTab('licencia');
      return;
    }
    setPwdError('');
    saveBranding(branding);
    localStorage.setItem('arpm_messaging', JSON.stringify(msgConfig));
    // Guardar config IA (misma clave que lee AIChat y AnteproyectoImportModal)
    const aiKeys = ['aiProvider','aiLocalUrl','aiLocalModel','claudeApiKey','claudeModel','openaiApiKey','openaiModel','aiSubtasks','aiEstimate','aiPerformance','aiOverrun','adminEmail','adminPassword'];
    const aiConfig = Object.fromEntries(aiKeys.map(k => [k, form[k]]));
    localStorage.setItem('arpm_settings', JSON.stringify(aiConfig));
    setSaved(true);
    setTimeout(() => setSaved(false), 3000);
  };

  const handleLogoUpload = (file) => {
    if (!file) return;
    const ext = file.name.split('.').pop().toLowerCase();
    if (!['png','jpg','jpeg','svg','webp'].includes(ext)) return;
    const reader = new FileReader();
    reader.onload = e => {
      const next = { ...branding, logo: e.target.result };
      setBranding(next);
      setSaved(false);
    };
    reader.readAsDataURL(file);
  };

  const handleRemoveLogo = () => {
    const next = { ...branding, logo: null };
    setBranding(next);
    setSaved(false);
  };

  return (
    <div className="space-y-5 pb-6 max-w-4xl">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">ConfiguraciÃ³n</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">Datos de la empresa, fiscales y parÃ¡metros del sistema</p>
        </div>
        <button onClick={handleSave}
          disabled={!isAdmin && ['empresa','fiscal','licencia'].includes(tab)}
          title={!isAdmin && ['empresa','fiscal','licencia'].includes(tab) ? 'Solo el administrador puede guardar esta secciÃ³n' : undefined}
          className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all shadow-sm ${!isAdmin && ['empresa','fiscal','licencia'].includes(tab) ? 'bg-slate-200 dark:bg-surface-700 text-slate-400 dark:text-gray-600 cursor-not-allowed' : saved ? 'bg-emerald-600 text-white cursor-pointer' : 'bg-blue-600 hover:bg-blue-700 text-white cursor-pointer'}`}>
          {saved
            ? <><svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>Guardado</>
            : <><svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"/></svg>Guardar cambios</>
          }
        </button>
      </div>

      <div className="flex gap-5">
        {/* Sidebar nav */}
        <nav className="w-44 flex-shrink-0 space-y-1">
          {TABS.map(t => (
            <button key={t.key} onClick={()=>setTab(t.key)}
              className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm transition-all cursor-pointer text-left ${tab===t.key ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 font-medium' : 'text-slate-500 dark:text-gray-400 hover:bg-slate-100 dark:hover:bg-surface-700 hover:text-slate-800 dark:hover:text-gray-200'}`}>
              <svg className="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d={t.icon}/></svg>
              {t.label}
            </button>
          ))}
        </nav>

        {/* Content */}
        <div className="flex-1 bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm p-6 space-y-6">

          {/* â”€â”€ EMPRESA â”€â”€ */}
          {tab === 'empresa' && <>
            {!isAdmin && <AdminBanner />}
            <div className={!isAdmin ? "pointer-events-none select-none opacity-60" : ""}>
            <SectionTitle>Identidad de la empresa</SectionTitle>

            {/* Logo + Branding del sistema */}
            <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600 space-y-4">
              <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-widest">Marca del sistema</p>
              <div className="flex items-center gap-5">
                {/* Preview */}
                <div
                  onClick={() => logoRef.current.click()}
                  className="w-20 h-20 rounded-xl bg-blue-600 flex items-center justify-center shadow-sm flex-shrink-0 overflow-hidden cursor-pointer hover:opacity-90 transition-opacity relative group">
                  {branding.logo
                    ? <img src={branding.logo} alt="logo" className="w-full h-full object-cover"/>
                    : <span className="text-white text-xl font-bold">AR</span>
                  }
                  <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center rounded-xl">
                    <svg className="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/><path strokeLinecap="round" strokeLinejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                  </div>
                </div>
                <input ref={logoRef} type="file" accept=".png,.jpg,.jpeg,.svg,.webp" className="hidden"
                  onChange={e => handleLogoUpload(e.target.files[0])}/>
                <div className="flex-1 space-y-3">
                  <div>
                    <p className="text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Nombre del sistema <span className="font-normal text-slate-400">(aparece en el sidebar)</span></p>
                    <Input value={branding.appName || ''} onChange={e => setBranding(b => ({...b, appName: e.target.value}))} placeholder="AR Project"/>
                  </div>
                  <div>
                    <p className="text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">SubtÃ­tulo</p>
                    <Input value={branding.appSubtitle || ''} onChange={e => setBranding(b => ({...b, appSubtitle: e.target.value}))} placeholder="Manager"/>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-3 pt-1">
                <button onClick={() => logoRef.current.click()}
                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline cursor-pointer font-medium">
                  {branding.logo ? 'Cambiar logo' : 'Subir logo'}
                </button>
                {branding.logo && <>
                  <span className="text-slate-200 dark:text-surface-600">|</span>
                  <button onClick={handleRemoveLogo} className="text-xs text-red-500 hover:underline cursor-pointer">Eliminar logo</button>
                </>}
                <span className="text-xs text-slate-400 dark:text-gray-600 ml-auto">PNG, JPG, SVG, WebP Â· mÃ¡x 2 MB Â· 200Ã—200px recomendado</span>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Field label="RazÃ³n social *">
                <Input value={form.companyName} onChange={e=>set('companyName',e.target.value)} placeholder="Nombre legal de la empresa"/>
              </Field>
              <Field label="Nombre comercial">
                <Input value={form.tradeName} onChange={e=>set('tradeName',e.target.value)} placeholder="Si difiere de la razÃ³n social"/>
              </Field>
            </div>

            <div className="grid grid-cols-3 gap-4">
              <Field label="Tipo de identificaciÃ³n">
                <Select value={form.taxIdType} onChange={e=>set('taxIdType',e.target.value)}
                  options={['NIT','RUT','RFC','RUC','CUIT','RUT-CL','Otro']}/>
              </Field>
              <Field label="NÃºmero de identificaciÃ³n tributaria *" hint="Ej: 900.123.456-7">
                <Input value={form.taxId} onChange={e=>set('taxId',e.target.value)} placeholder="NÃºmero fiscal" mono/>
              </Field>
              <Field label="Tipo de sociedad">
                <Select value={form.companyType} onChange={e=>set('companyType',e.target.value)}
                  options={['SAS','SA','LTDA','SRL','EIRL','Individual','Otro']}/>
              </Field>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Field label="Representante legal">
                <Input value={form.legalRep} onChange={e=>set('legalRep',e.target.value)} placeholder="Nombre completo"/>
              </Field>
              <Field label="Sector / Industria">
                <Select value={form.industry} onChange={e=>set('industry',e.target.value)}
                  options={['CONSTRUCCIÃ“N','MANUFACTURA','TECNOLOGÃA','CONSULTORÃA','SALUD','EDUCACIÃ“N','ENERGÃA','MINERÃA','AGRO','RETAIL','FINANCIERO','OTRO']}/>
              </Field>
            </div>

            <Field label="Sitio web">
              <Input value={form.website} onChange={e=>set('website',e.target.value)} placeholder="https://www.miempresa.com"/>
            </Field>

            <SectionTitle>DirecciÃ³n</SectionTitle>
            <Field label="DirecciÃ³n completa">
              <Input value={form.address} onChange={e=>set('address',e.target.value)} placeholder="Calle, nÃºmero, piso, oficina"/>
            </Field>
            <div className="grid grid-cols-2 gap-4">
              <Field label="Ciudad">
                <Input value={form.city} onChange={e=>set('city',e.target.value)} placeholder="Ciudad"/>
              </Field>
              <Field label="Departamento / Estado / Provincia">
                <Input value={form.state} onChange={e=>set('state',e.target.value)} placeholder="Departamento o estado"/>
              </Field>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <Field label="PaÃ­s">
                <Select value={form.country} onChange={e=>set('country',e.target.value)}
                  options={['Colombia','MÃ©xico','Argentina','Chile','PerÃº','Venezuela','Ecuador','Bolivia','Paraguay','Uruguay','EspaÃ±a','Estados Unidos','Otro']}/>
              </Field>
              <Field label="CÃ³digo postal">
                <Input value={form.zip} onChange={e=>set('zip',e.target.value)} placeholder="CÃ³digo postal" mono/>
              </Field>
            </div>
            </div>
          </>}

          {/* â”€â”€ CONTACTO â”€â”€ */}
          {tab === 'contacto' && <>
            <SectionTitle>InformaciÃ³n de contacto</SectionTitle>
            <div className="grid grid-cols-2 gap-4">
              <Field label="TelÃ©fono principal">
                <Input value={form.phone} onChange={e=>set('phone',e.target.value)} placeholder="+57 601 555 0100" mono/>
              </Field>
              <Field label="Celular / MÃ³vil">
                <Input value={form.mobile} onChange={e=>set('mobile',e.target.value)} placeholder="+57 310 555 0200" mono/>
              </Field>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <Field label="Email corporativo general">
                <Input type="email" value={form.email} onChange={e=>set('email',e.target.value)} placeholder="contacto@empresa.com"/>
              </Field>
              <Field label="Email departamento finanzas / compras" hint="Se usarÃ¡ para envÃ­o de Ã³rdenes de compra y facturas">
                <Input type="email" value={form.emailFinance} onChange={e=>set('emailFinance',e.target.value)} placeholder="finanzas@empresa.com"/>
              </Field>
            </div>
          </>}

          {/* â”€â”€ FISCAL & MONEDA â”€â”€ */}
          {tab === 'fiscal' && <>
            {!isAdmin && <AdminBanner />}
            <div className={!isAdmin ? "pointer-events-none select-none opacity-60" : ""}>
            <SectionTitle>Moneda y formato</SectionTitle>
            <div className="grid grid-cols-3 gap-4">
              <Field label="Moneda principal">
                <Select value={form.currency} onChange={e=>set('currency',e.target.value)}
                  options={[
                    {value:'COP',label:'COP â€” Peso colombiano'},
                    {value:'MXN',label:'MXN â€” Peso mexicano'},
                    {value:'ARS',label:'ARS â€” Peso argentino'},
                    {value:'CLP',label:'CLP â€” Peso chileno'},
                    {value:'PEN',label:'PEN â€” Sol peruano'},
                    {value:'USD',label:'USD â€” DÃ³lar americano'},
                    {value:'EUR',label:'EUR â€” Euro'},
                  ]}/>
              </Field>
              <Field label="SÃ­mbolo de moneda">
                <Input value={form.currencySymbol} onChange={e=>set('currencySymbol',e.target.value)} placeholder="$" mono/>
              </Field>
              <Field label="Formato de fecha">
                <Select value={form.dateFormat} onChange={e=>set('dateFormat',e.target.value)}
                  options={['DD/MM/YYYY','MM/DD/YYYY','YYYY-MM-DD']}/>
              </Field>
            </div>

            <SectionTitle>Impuestos</SectionTitle>
            <div className="grid grid-cols-2 gap-4">
              <Field label="Nombre del impuesto principal" hint="Ej: IVA, IGV, ISR, VAT">
                <Input value={form.taxName} onChange={e=>set('taxName',e.target.value)} placeholder="IVA"/>
              </Field>
              <Field label="Tasa (%)" hint="Porcentaje aplicado por defecto en presupuestos y OC">
                <Input type="number" value={form.taxRate} onChange={e=>set('taxRate',Number(e.target.value))} placeholder="19" mono/>
              </Field>
            </div>

            <SectionTitle>AÃ±o fiscal</SectionTitle>
            <Field label="Inicio del aÃ±o fiscal" hint="Formato MM-DD. Ej: 01-01 = 1 de enero, 04-01 = 1 de abril">
              <div className="max-w-[160px]">
                <Input value={form.fiscalYearStart} onChange={e=>set('fiscalYearStart',e.target.value)} placeholder="01-01" mono/>
              </div>
            </Field>
            </div>
          </>}

          {/* â”€â”€ PROYECTOS â”€â”€ */}
          {tab === 'proyectos' && <>
            <SectionTitle>Calendario laboral por defecto</SectionTitle>
            <div className="grid grid-cols-2 gap-4">
              <Field label="Horas de trabajo por dÃ­a" hint="Usado para calcular duraciÃ³n en horas">
                <Input type="number" value={form.defaultHoursPerDay} onChange={e=>set('defaultHoursPerDay',Number(e.target.value))} placeholder="8" mono/>
              </Field>
              <Field label="DÃ­as laborales por semana">
                <Select value={form.defaultDaysPerWeek} onChange={e=>set('defaultDaysPerWeek',Number(e.target.value))}
                  options={[{value:5,label:'5 dÃ­as (L-V)'},{value:6,label:'6 dÃ­as (L-S)'},{value:7,label:'7 dÃ­as'}]}/>
              </Field>
            </div>

            <SectionTitle>Prefijos de numeraciÃ³n</SectionTitle>
            <p className="text-xs text-slate-400 dark:text-gray-500 -mt-3 mb-4">Los cÃ³digos se generan automÃ¡ticamente usando el prefijo + aÃ±o + nÃºmero secuencial.</p>
            <div className="grid grid-cols-3 gap-4">
              <Field label="Proyectos" hint="Ej: PRY â†’ PRY-2026-004">
                <Input value={form.projectCodePrefix} onChange={e=>set('projectCodePrefix',e.target.value)} placeholder="PRY" mono/>
              </Field>
              <Field label="Ã“rdenes de Trabajo" hint="Ej: OT â†’ OT-001">
                <Input value={form.otCodePrefix} onChange={e=>set('otCodePrefix',e.target.value)} placeholder="OT" mono/>
              </Field>
              <Field label="Solicitudes de CotizaciÃ³n" hint="Ej: RFQ â†’ RFQ-2026-001">
                <Input value={form.rfqCodePrefix} onChange={e=>set('rfqCodePrefix',e.target.value)} placeholder="RFQ" mono/>
              </Field>
            </div>

            <SectionTitle>Vista previa de cÃ³digos generados</SectionTitle>
            <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600 grid grid-cols-3 gap-4 text-center">
              {[
                { label:'Proyecto',             code:`${form.projectCodePrefix}-2026-001` },
                { label:'Orden de Trabajo',     code:`${form.otCodePrefix}-001` },
                { label:'Solicitud CotizaciÃ³n', code:`${form.rfqCodePrefix}-2026-001` },
              ].map(({label,code})=>(
                <div key={label}>
                  <p className="text-xs text-slate-400 dark:text-gray-500 mb-1">{label}</p>
                  <p className="text-sm font-mono font-bold text-blue-600 dark:text-blue-400">{code}</p>
                </div>
              ))}
            </div>
          </>}

          {/* â”€â”€ LICENCIA â”€â”€ */}
          {tab === 'licencia' && <>
            {!isAdmin && <AdminBanner />}
            <div className={!isAdmin ? "pointer-events-none select-none opacity-60" : ""}>
            {/* Estado actual */}
            <div className="flex items-center gap-4 bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-200 dark:border-emerald-500/25 rounded-2xl p-5">
              <div className="w-12 h-12 rounded-xl bg-emerald-600 flex items-center justify-center flex-shrink-0">
                <svg className="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
              </div>
              <div className="flex-1">
                <p className="text-sm font-bold text-emerald-800 dark:text-emerald-300">Licencia Enterprise â€” Activa</p>
                <p className="text-xs text-emerald-700 dark:text-emerald-400 mt-0.5">Vence el 31 de diciembre de 2026 Â· 25 usuarios incluidos</p>
              </div>
              <span className="text-xs font-bold bg-emerald-600 text-white px-3 py-1 rounded-full">ACTIVA</span>
            </div>

            <SectionTitle>Datos de registro</SectionTitle>
            <div className="grid grid-cols-2 gap-4">
              <Field label="Empresa registrada">
                <Input value={form.licenseCompany} onChange={e=>set('licenseCompany',e.target.value)} placeholder="Nombre de la empresa"/>
              </Field>
              <Field label="Email de registro" hint="Asociado a su cuenta en el portal de licencias">
                <Input type="email" value={form.licenseEmail} onChange={e=>set('licenseEmail',e.target.value)} placeholder="email@empresa.com"/>
              </Field>
            </div>

            <Field label="Clave de licencia" hint="No comparta esta clave. Ingrese una nueva clave si adquiriÃ³ una licencia adicional.">
              <div className="flex gap-2">
                <Input value={form.licenseKey} onChange={e=>set('licenseKey',e.target.value)} placeholder="ARPM-XXXX-XXXX-XXXX-XXXX-XXXX" mono/>
                <button
                  onClick={()=>{ navigator.clipboard?.writeText(form.licenseKey); }}
                  title="Copiar clave"
                  className="flex-shrink-0 px-3 py-2 text-sm border border-slate-200 dark:border-surface-600 rounded-lg text-slate-500 dark:text-gray-400 hover:bg-slate-100 dark:hover:bg-surface-700 transition cursor-pointer">
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                </button>
              </div>
            </Field>

            <button className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg border border-blue-300 dark:border-blue-500/40 text-blue-700 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition cursor-pointer">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
              Verificar y activar licencia
            </button>

            <SectionTitle>Plan actual</SectionTitle>
            <div className="grid grid-cols-3 gap-3">
              {[
                { plan:'Starter',    price:'$49/mes',   users:5,   color:'bg-slate-100 dark:bg-surface-700 border-slate-200 dark:border-surface-600', active:false },
                { plan:'Pro',        price:'$149/mes',  users:15,  color:'bg-slate-100 dark:bg-surface-700 border-slate-200 dark:border-surface-600', active:false },
                { plan:'Enterprise', price:'$399/mes',  users:999, color:'bg-blue-50 dark:bg-blue-500/10 border-blue-300 dark:border-blue-500/40',    active:true  },
              ].map(({plan,price,users,color,active})=>(
                <div key={plan} className={`rounded-xl p-4 border ${color} ${active ? 'ring-2 ring-blue-500' : ''}`}>
                  <div className="flex items-center justify-between mb-2">
                    <p className={`text-sm font-bold ${active ? 'text-blue-700 dark:text-blue-400' : 'text-slate-700 dark:text-gray-300'}`}>{plan}</p>
                    {active && <span className="text-xs font-bold text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-500/20 px-2 py-0.5 rounded-full">Tu plan</span>}
                  </div>
                  <p className={`text-lg font-bold tabular-nums ${active ? 'text-blue-800 dark:text-blue-300' : 'text-slate-600 dark:text-gray-400'}`}>{price}</p>
                  <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">{users === 999 ? 'Usuarios ilimitados' : `Hasta ${users} usuarios`}</p>
                </div>
              ))}
            </div>

            <SectionTitle>Acceso de administrador</SectionTitle>
            <Field label="Email de acceso" hint="Correo con el que se inicia sesiÃ³n en el sistema.">
              <Input type="email" value={form.adminEmail || ''} onChange={e=>set('adminEmail',e.target.value)} placeholder="admin@arpm.com"/>
            </Field>
            <Field label="Nueva contraseÃ±a" hint="Deja en blanco para no cambiarla. MÃ­nimo 8 caracteres, incluye mayÃºscula y sÃ­mbolo.">
              <Input type="password" value={form.adminPassword || ''} onChange={e=>{set('adminPassword',e.target.value); setPwdError('');}} placeholder="â€¢â€¢â€¢â€¢â€¢â€¢â€¢â€¢"/>
            </Field>
            <Field label="Confirmar nueva contraseÃ±a">
              <Input type="password" value={form.adminPasswordConfirm || ''} onChange={e=>{set('adminPasswordConfirm',e.target.value); setPwdError('');}} placeholder="â€¢â€¢â€¢â€¢â€¢â€¢â€¢â€¢"/>
              {pwdError && <p className="mt-1 text-xs text-red-500 font-medium">{pwdError}</p>}
            </Field>

            <SectionTitle>NumeraciÃ³n de proyectos</SectionTitle>
            <div className="flex items-center justify-between bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
              <div>
                <p className="text-sm font-medium text-slate-700 dark:text-gray-300">Contador actual</p>
                <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">
                  PrÃ³ximo proyecto: <span className="font-mono font-semibold text-blue-600 dark:text-blue-400">#{String(parseInt(localStorage.getItem('arpm_project_seq') || '0', 10) + 1).padStart(3, '0')}</span>
                </p>
              </div>
              <button
                onClick={() => { if (window.confirm('Â¿Resetear el contador de proyectos a 0?')) { localStorage.setItem('arpm_project_seq', '0'); setSaved(false); window.location.reload(); } }}
                className="flex items-center gap-2 px-3 py-2 text-sm rounded-lg border border-red-200 dark:border-red-500/30 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 transition cursor-pointer">
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                Resetear a 001
              </button>
            </div>

            <SectionTitle>InformaciÃ³n del sistema</SectionTitle>
            <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600 grid grid-cols-2 gap-y-3 text-sm">
              {[
                { label:'VersiÃ³n del software',   value:'AR-ProjectManagement v1.0.0' },
                { label:'Tipo de instalaciÃ³n',    value:'Cloud / SaaS' },
                { label:'Usuarios activos',       value:'7 de 25 licencias usadas' },
                { label:'PrÃ³xima renovaciÃ³n',     value:'31 dic 2026' },
                { label:'Soporte tÃ©cnico',        value:'soporte@arelectronics.com' },
                { label:'Portal de licencias',    value:'licencias.arelectronics.com' },
              ].map(({label,value})=>(
                <div key={label}>
                  <p className="text-xs text-slate-400 dark:text-gray-500">{label}</p>
                  <p className="text-sm font-medium text-slate-700 dark:text-gray-300 mt-0.5">{value}</p>
                </div>
              ))}
            </div>
            </div>
          </>}

          {/* â”€â”€ NOTIFICACIONES â”€â”€ */}
          {tab === 'notif' && <>
            <SectionTitle>Alertas del sistema</SectionTitle>
            <div className="space-y-4">
              <Toggle checked={form.notifyOverdueTask} onChange={v=>set('notifyOverdueTask',v)}
                label="Alertar cuando una tarea estÃ© vencida o prÃ³xima a vencer"/>
              <Toggle checked={form.notifyNewOT} onChange={v=>set('notifyNewOT',v)}
                label="Notificar al responsable cuando se crea una nueva Orden de Trabajo"/>

              <div className="space-y-3">
                <Toggle checked={form.notifyBudgetAlert} onChange={v=>set('notifyBudgetAlert',v)}
                  label="Alertar cuando el presupuesto comprometido supere un umbral"/>
                {form.notifyBudgetAlert && (
                  <div className="ml-11 flex items-center gap-3">
                    <span className="text-sm text-slate-500 dark:text-gray-400 whitespace-nowrap">Umbral de alerta:</span>
                    <input type="range" min={50} max={100} step={5} value={form.notifyBudgetThreshold}
                      onChange={e=>set('notifyBudgetThreshold',Number(e.target.value))}
                      className="flex-1 accent-blue-600"/>
                    <span className="text-sm font-bold text-blue-600 dark:text-blue-400 w-12 tabular-nums">{form.notifyBudgetThreshold}%</span>
                  </div>
                )}
              </div>
            </div>

            <SectionTitle>Flujo de caja</SectionTitle>
            <div className="bg-amber-50 dark:bg-amber-500/10 border border-amber-100 dark:border-amber-500/20 rounded-xl px-4 py-3 flex items-start gap-3">
              <svg className="w-4 h-4 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
              <div>
                <p className="text-sm font-semibold text-amber-800 dark:text-amber-300">Alarma de flujo de caja crÃ­tico</p>
                <p className="text-xs text-amber-700 dark:text-amber-400 mt-0.5">
                  El sistema alertarÃ¡ automÃ¡ticamente cuando existan compromisos de pago (OC aprobadas, OTs con costo) y no haya flujo de caja registrado para cubrirlos. Esta alerta aparece en el Dashboard y en el mÃ³dulo EVM.
                </p>
              </div>
            </div>
            <Toggle checked={true} onChange={()=>{}}
              label="Activar alarma de flujo de caja insuficiente"/>
          </>}

          {/* â”€â”€ INTELIGENCIA IA â”€â”€ */}
          {tab === 'ia' && <>
            <SectionTitle>Motor de Inteligencia Artificial</SectionTitle>
            <div className="bg-blue-50 dark:bg-blue-500/10 border border-blue-100 dark:border-blue-500/20 rounded-xl px-4 py-3 flex items-start gap-3">
              <svg className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
              <p className="text-xs text-blue-700 dark:text-blue-300">
                La IA analiza el historial de tareas completadas para estimar subtareas, predecir horas reales y evaluar el rendimiento por trabajador. Los datos <strong>nunca salen de tu empresa</strong> si usas IA local.
              </p>
            </div>

            {/* SelecciÃ³n de proveedor */}
            <Field label="Proveedor de IA">
              <div className="space-y-2">
                {[
                  { key:'ollama',  label:'IA Local (Ollama / LM Studio)', desc:'Tus datos no salen de la empresa. Requiere Ollama instalado localmente.', badge:'Recomendado', badgeColor:'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400' },
                  { key:'claude',  label:'Claude API (Anthropic)',         desc:'Modelos Claude de Anthropic. Requiere API key.', badge:null },
                  { key:'openai',  label:'OpenAI (GPT-4o / GPT-4)',        desc:'Modelos de OpenAI. Requiere API key.', badge:null },
                  { key:'none',    label:'Sin IA â€” solo gestiÃ³n manual',   desc:'Desactiva todas las funciones de inteligencia artificial.', badge:null },
                ].map(p => (
                  <label key={p.key} className={`flex items-start gap-3 p-3 rounded-xl border cursor-pointer transition-all ${form.aiProvider===p.key ? 'border-blue-500 bg-blue-50 dark:bg-blue-500/10' : 'border-slate-200 dark:border-surface-600 hover:border-slate-300 dark:hover:border-surface-500'}`}>
                    <input type="radio" name="aiProvider" value={p.key} checked={form.aiProvider===p.key}
                      onChange={()=>setForm(x=>({...x,aiProvider:p.key}))}
                      className="mt-0.5 accent-blue-600"/>
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-semibold text-slate-800 dark:text-white">{p.label}</span>
                        {p.badge && <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${p.badgeColor}`}>{p.badge}</span>}
                      </div>
                      <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{p.desc}</p>
                    </div>
                  </label>
                ))}
              </div>
            </Field>

            {/* Config Ollama */}
            {form.aiProvider === 'ollama' && (
              <div className="space-y-3 border border-slate-200 dark:border-surface-600 rounded-xl p-4">
                <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-widest">ConfiguraciÃ³n Ollama / LM Studio</p>
                <Field label="URL del servidor local" hint="Por defecto Ollama usa http://localhost:11434">
                  <input className="field-input" value={form.aiLocalUrl||'http://localhost:11434'}
                    onChange={e=>setForm(x=>({...x,aiLocalUrl:e.target.value}))} placeholder="http://localhost:11434"/>
                </Field>
                <Field label="Modelo a usar" hint="Ej: llama3, mistral, deepseek-r1, phi3, gemma3">
                  <input className="field-input" value={form.aiLocalModel||''} placeholder="llama3"
                    onChange={e=>setForm(x=>({...x,aiLocalModel:e.target.value}))}/>
                </Field>
                <button className="flex items-center gap-2 px-3 py-1.5 text-xs font-semibold border border-slate-200 dark:border-surface-600 rounded-lg text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 cursor-pointer transition-colors">
                  <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                  Probar conexiÃ³n
                </button>
              </div>
            )}

            {/* Config Claude */}
            {form.aiProvider === 'claude' && (
              <div className="space-y-3 border border-slate-200 dark:border-surface-600 rounded-xl p-4">
                <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-widest">ConfiguraciÃ³n Claude API</p>
                <Field label="API Key" hint="Empieza con sk-ant-... â€” se guarda encriptada localmente">
                  <input type="password" className="field-input font-mono" value={form.claudeApiKey||''} placeholder="sk-ant-api03-..."
                    onChange={e=>setForm(x=>({...x,claudeApiKey:e.target.value}))}/>
                </Field>
                <Field label="Modelo">
                  <select className="field-input" value={form.claudeModel||'claude-sonnet-4-6'}
                    onChange={e=>setForm(x=>({...x,claudeModel:e.target.value}))}>
                    <option value="claude-sonnet-4-6">Claude Sonnet 4.6 (recomendado)</option>
                    <option value="claude-haiku-4-5-20251001">Claude Haiku 4.5 (mÃ¡s rÃ¡pido, menor costo)</option>
                    <option value="claude-opus-4-8">Claude Opus 4.8 (mayor capacidad)</option>
                  </select>
                </Field>
              </div>
            )}

            {/* Config OpenAI */}
            {form.aiProvider === 'openai' && (
              <div className="space-y-3 border border-slate-200 dark:border-surface-600 rounded-xl p-4">
                <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-widest">ConfiguraciÃ³n OpenAI</p>
                <Field label="API Key" hint="Empieza con sk-... â€” se guarda encriptada localmente">
                  <input type="password" className="field-input font-mono" value={form.openaiApiKey||''} placeholder="sk-..."
                    onChange={e=>setForm(x=>({...x,openaiApiKey:e.target.value}))}/>
                </Field>
                <Field label="Modelo">
                  <select className="field-input" value={form.openaiModel||'gpt-4o'}
                    onChange={e=>setForm(x=>({...x,openaiModel:e.target.value}))}>
                    <option value="gpt-4o">GPT-4o (recomendado)</option>
                    <option value="gpt-4o-mini">GPT-4o Mini (mÃ¡s rÃ¡pido, menor costo)</option>
                    <option value="gpt-4-turbo">GPT-4 Turbo</option>
                  </select>
                </Field>
              </div>
            )}

            {/* Funciones IA */}
            {form.aiProvider !== 'none' && (
              <>
                <SectionTitle>Funciones activadas</SectionTitle>
                <div className="space-y-2">
                  {[
                    { key:'aiSubtasks',   label:'Proponer subtareas automÃ¡ticamente', desc:'Al crear una tarea principal, la IA sugiere subtareas basadas en el tipo de trabajo e historial.' },
                    { key:'aiEstimate',   label:'Estimar horas por subtarea',         desc:'La IA sugiere horas basadas en el historial de tareas similares completadas.' },
                    { key:'aiPerformance',label:'AnÃ¡lisis de rendimiento por trabajador', desc:'Compara horas estimadas vs reales por persona y tipo de tarea. Genera alertas tempranas.' },
                    { key:'aiOverrun',    label:'Alerta predictiva de desvÃ­o',        desc:'La IA detecta tareas en riesgo de exceder el presupuesto antes de que ocurra.' },
                  ].map(f => (
                    <div key={f.key} className="flex items-start gap-3 p-3 border border-slate-200 dark:border-surface-600 rounded-xl">
                      <input type="checkbox" checked={form[f.key]!==false} onChange={e=>setForm(x=>({...x,[f.key]:e.target.checked}))}
                        className="mt-0.5 accent-blue-600 cursor-pointer"/>
                      <div>
                        <p className="text-sm font-semibold text-slate-800 dark:text-white">{f.label}</p>
                        <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{f.desc}</p>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="bg-amber-50 dark:bg-amber-500/10 border border-amber-100 dark:border-amber-500/20 rounded-xl px-4 py-3">
                  <p className="text-xs text-amber-700 dark:text-amber-400">
                    <strong>Fase 1 activa:</strong> El sistema ya captura horas reales al completar tareas.
                    Las funciones de IA estarÃ¡n disponibles cuando el proyecto tenga al menos 20 tareas completadas con horas registradas.
                  </p>
                </div>
              </>
            )}
          </>}

          {/* â”€â”€ MENSAJERÃA â”€â”€ */}
          {tab === 'mensajeria' && <MensajeriaTab config={msgConfig} setMsg={setMsg} />}

        </div>
      </div>
    </div>
  );
}

/* â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
   MensajeriaTab â€” configuraciÃ³n de canales de notificaciÃ³n
â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ */
function MensajeriaTab({ config, setMsg }) {
  const [testStatus, setTestStatus] = useState({});

  const setStatus = (channel, msg, isErr = false) => {
    setTestStatus(s => ({ ...s, [channel]: { msg, isErr } }));
    setTimeout(() => setTestStatus(s => ({ ...s, [channel]: null })), 5000);
  };

  const handleTestEmail = async () => {
    try {
      await notificationService.sendEmail({
        to: config.emailjsToEmail,
        subject: 'Prueba AR Project Management',
        body: 'Este es un mensaje de prueba enviado desde AR Project Management.',
      });
      setStatus('email', 'Email de prueba enviado correctamente.');
    } catch (err) {
      setStatus('email', err.message, true);
    }
  };

  const handleTestWhatsApp = () => {
    try {
      notificationService.sendWhatsApp({
        phone: config.whatsappPhone,
        message: 'Prueba de notificaciÃ³n desde AR Project Management.',
      });
      setStatus('whatsapp', 'Se abriÃ³ WhatsApp con el mensaje de prueba.');
    } catch (err) {
      setStatus('whatsapp', err.message, true);
    }
  };

  const handleTestTelegram = async () => {
    try {
      await notificationService.sendTelegram({
        chatId: config.telegramChatId,
        message: 'Prueba de notificaciÃ³n desde AR Project Management.',
      });
      setStatus('telegram', 'Mensaje de prueba enviado a Telegram correctamente.');
    } catch (err) {
      setStatus('telegram', err.message, true);
    }
  };

  const handleTestMessenger = () => {
    try {
      notificationService.sendMessenger({ pageId: config.messengerPageId });
      setStatus('messenger', 'Se abriÃ³ Messenger en una nueva pestaÃ±a.');
    } catch (err) {
      setStatus('messenger', err.message, true);
    }
  };

  return (
    <div className="space-y-6">
      {/* Banner nota de arquitectura */}
      <div className="bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/25 rounded-xl px-4 py-3 flex items-start gap-3">
        <svg className="w-4 h-4 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        <p className="text-xs text-amber-800 dark:text-amber-300">
          <strong>Nota de arquitectura:</strong> Para envÃ­o automÃ¡tico de emails en segundo plano (sin abrir ventana), configura el backend Node.js con Nodemailer o SendGrid.
        </p>
      </div>

      {/* â”€â”€ EMAIL â”€â”€ */}
      <div className="border border-slate-200 dark:border-surface-600 rounded-xl p-4 space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
            <span className="text-sm font-semibold text-slate-800 dark:text-white">Email (EmailJS)</span>
          </div>
          <Toggle checked={!!config.emailEnabled} onChange={v => setMsg('emailEnabled', v)} label="" />
        </div>
        {config.emailEnabled && (
          <div className="space-y-3 pt-1">
            <div className="grid grid-cols-2 gap-3">
              <Field label="Service ID">
                <Input value={config.emailjsServiceId || ''} onChange={e => setMsg('emailjsServiceId', e.target.value)} placeholder="service_xxxxxxx" mono />
              </Field>
              <Field label="Template ID">
                <Input value={config.emailjsTemplateId || ''} onChange={e => setMsg('emailjsTemplateId', e.target.value)} placeholder="template_xxxxxxx" mono />
              </Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Public Key">
                <Input value={config.emailjsPublicKey || ''} onChange={e => setMsg('emailjsPublicKey', e.target.value)} placeholder="XXXXXXXXXXXXXXXXXX" mono />
              </Field>
              <Field label="Email destinatario">
                <Input type="email" value={config.emailjsToEmail || ''} onChange={e => setMsg('emailjsToEmail', e.target.value)} placeholder="notificaciones@empresa.com" />
              </Field>
            </div>
            <div className="flex items-center gap-3">
              <button onClick={handleTestEmail}
                className="px-3 py-1.5 text-xs font-semibold bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors cursor-pointer">
                Probar envÃ­o
              </button>
              <p className="text-xs text-slate-400 dark:text-gray-500">Crea cuenta gratis en <a href="https://emailjs.com" target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">emailjs.com</a> Â· 200 emails/mes gratis</p>
            </div>
            {testStatus.email && (
              <p className={`text-xs font-medium ${testStatus.email.isErr ? 'text-red-500' : 'text-emerald-600 dark:text-emerald-400'}`}>{testStatus.email.msg}</p>
            )}
          </div>
        )}
      </div>

      {/* â”€â”€ WHATSAPP â”€â”€ */}
      <div className="border border-slate-200 dark:border-surface-600 rounded-xl p-4 space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-emerald-500" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
            <span className="text-sm font-semibold text-slate-800 dark:text-white">WhatsApp</span>
          </div>
          <Toggle checked={!!config.whatsappEnabled} onChange={v => setMsg('whatsappEnabled', v)} label="" />
        </div>
        {config.whatsappEnabled && (
          <div className="space-y-3 pt-1">
            <Field label="NÃºmero WhatsApp" hint="Abre WhatsApp Web con el mensaje pre-escrito. No requiere API.">
              <Input value={config.whatsappPhone || ''} onChange={e => setMsg('whatsappPhone', e.target.value)} placeholder="+573105550200" mono />
            </Field>
            <div className="flex items-center gap-3">
              <button onClick={handleTestWhatsApp}
                className="px-3 py-1.5 text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors cursor-pointer">
                Probar enlace
              </button>
            </div>
            {testStatus.whatsapp && (
              <p className={`text-xs font-medium ${testStatus.whatsapp.isErr ? 'text-red-500' : 'text-emerald-600 dark:text-emerald-400'}`}>{testStatus.whatsapp.msg}</p>
            )}
          </div>
        )}
      </div>

      {/* â”€â”€ TELEGRAM â”€â”€ */}
      <div className="border border-slate-200 dark:border-surface-600 rounded-xl p-4 space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-sky-500" fill="currentColor" viewBox="0 0 24 24"><path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>
            <span className="text-sm font-semibold text-slate-800 dark:text-white">Telegram Bot</span>
          </div>
          <Toggle checked={!!config.telegramEnabled} onChange={v => setMsg('telegramEnabled', v)} label="" />
        </div>
        {config.telegramEnabled && (
          <div className="space-y-3 pt-1">
            <div className="grid grid-cols-2 gap-3">
              <Field label="Bot Token" hint="Crea un bot con @BotFather en Telegram y obtÃ©n el token.">
                <Input value={config.telegramToken || ''} onChange={e => setMsg('telegramToken', e.target.value)} placeholder="123456789:AAH..." mono />
              </Field>
              <Field label="Chat ID" hint="El Chat ID es el tuyo personal o el del grupo donde quieres recibir notificaciones.">
                <Input value={config.telegramChatId || ''} onChange={e => setMsg('telegramChatId', e.target.value)} placeholder="-1001234567890" mono />
              </Field>
            </div>
            <div className="flex items-center gap-3">
              <button onClick={handleTestTelegram}
                className="px-3 py-1.5 text-xs font-semibold bg-sky-600 hover:bg-sky-700 text-white rounded-lg transition-colors cursor-pointer">
                Enviar mensaje de prueba
              </button>
            </div>
            {testStatus.telegram && (
              <p className={`text-xs font-medium ${testStatus.telegram.isErr ? 'text-red-500' : 'text-emerald-600 dark:text-emerald-400'}`}>{testStatus.telegram.msg}</p>
            )}
          </div>
        )}
      </div>

      {/* â”€â”€ MESSENGER â”€â”€ */}
      <div className="border border-slate-200 dark:border-surface-600 rounded-xl p-4 space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-indigo-500" fill="currentColor" viewBox="0 0 24 24"><path d="M12 0C5.373 0 0 4.974 0 11.111c0 3.498 1.744 6.614 4.469 8.654V24l4.088-2.242c1.092.3 2.246.464 3.443.464 6.627 0 12-4.975 12-11.111C24 4.974 18.627 0 12 0zm1.191 14.963l-3.055-3.26-5.963 3.26L10.732 8l3.131 3.259L19.752 8l-6.561 6.963z"/></svg>
            <span className="text-sm font-semibold text-slate-800 dark:text-white">Messenger</span>
          </div>
          <Toggle checked={!!config.messengerEnabled} onChange={v => setMsg('messengerEnabled', v)} label="" />
        </div>
        {config.messengerEnabled && (
          <div className="space-y-3 pt-1">
            <Field label="Page ID de Facebook" hint="Abre el chat de tu pÃ¡gina de Facebook. El usuario debe haber iniciado conversaciÃ³n primero.">
              <Input value={config.messengerPageId || ''} onChange={e => setMsg('messengerPageId', e.target.value)} placeholder="123456789012345" mono />
            </Field>
            <div className="flex items-center gap-3">
              <button onClick={handleTestMessenger}
                className="px-3 py-1.5 text-xs font-semibold bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors cursor-pointer">
                Abrir Messenger
              </button>
            </div>
            {testStatus.messenger && (
              <p className={`text-xs font-medium ${testStatus.messenger.isErr ? 'text-red-500' : 'text-emerald-600 dark:text-emerald-400'}`}>{testStatus.messenger.msg}</p>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
