// AGENTFORGE-IA — CRM completo (resumen + leads + cuentas + pipeline + actividad + automatizaciones)
const CRM = () => {
  const { t, fmt, lang } = useI18n();
  const D = window.AF_CRM;
  const notify = (msg) => window.afNotify && window.afNotify(msg);
  const fileRef = React.useRef(null);

  const [contacts, setContacts] = React.useState([]);
  const [leadProfilesById, setLeadProfilesById] = React.useState({});
  const [timelineById, setTimelineById] = React.useState({});
  const [loading, setLoading] = React.useState(true);
  const [q, setQ] = React.useState('');
  const [type, setType] = React.useState('todos');
  const [stage, setStage] = React.useState('todas');
  const [view, setView] = React.useState('overview');
  const [open, setOpen] = React.useState(null);

  const [showCreate, setShowCreate] = React.useState(false);
  const [createSaving, setCreateSaving] = React.useState(false);
  const [createError, setCreateError] = React.useState('');
  const [draft, setDraft] = React.useState({
    name: '', email: '', company: '', title: '', phone: '', type: 'lead', stage: 'lead', country: 'España', ownerName: 'Admin',
  });

  const getToken = () => sessionStorage.getItem('af_token') || '';

  const loadContacts = React.useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/v1/crm/contacts', { headers: { Authorization: 'Bearer ' + getToken() } });
      if (!res.ok) throw new Error('crm');
      const data = await res.json();
      const mapped = data.map((c) => ({
        ...c,
        type: c.contact_type,
        initials: c.name.trim().split(/\s+/).map((x) => x[0]).join('').slice(0, 2).toUpperCase(),
        mrr: (c.mrr_cents || 0) / 100,
        arr: (c.arr_cents || 0) / 100,
        lastContactH: c.last_contact_at ? Math.round((Date.now() - new Date(c.last_contact_at).getTime()) / 3600000) : 999,
        health: Number(c.health || 75),
        sentiment: Number(c.sentiment || 0.7),
        ownerName: c.owner_name || 'Admin',
        owner: (c.owner_name || 'Admin').split(' ').map((x) => x[0]).join('').slice(0, 2).toUpperCase(),
        assignedAgent: c.assigned_agent || (D.agentNames && D.agentNames[0]) || 'Forge Agent',
        nextAction: c.next_action || 'Seguimiento manual',
      }));
      setContacts(mapped);

      try {
        const lr = await fetch('/api/v1/leads/items', { headers: { Authorization: 'Bearer ' + getToken() } });
        if (lr.ok) {
          const leadsItems = await lr.json();
          const byId = {};
          for (const item of (Array.isArray(leadsItems) ? leadsItems : [])) {
            byId[item.id] = item;
          }
          setLeadProfilesById(byId);
        } else {
          setLeadProfilesById({});
        }
      } catch (_) {
        setLeadProfilesById({});
      }

      const timelineEntries = await Promise.all(
        mapped.slice(0, 40).map(async (c) => {
          try {
            const tr = await fetch(`/api/v1/crm/contacts/${c.id}/timeline`, { headers: { Authorization: 'Bearer ' + getToken() } });
            if (!tr.ok) return [c.id, []];
            const ev = await tr.json();
            return [c.id, ev.map((x) => ({ ...x, t: new Date(x.created_at).getTime() }))];
          } catch (_) {
            return [c.id, []];
          }
        })
      );
      setTimelineById(Object.fromEntries(timelineEntries));
    } catch (_) {
      notify(t('crm.error_loading'));
    } finally {
      setLoading(false);
    }
  }, [lang]);

  React.useEffect(() => { loadContacts(); }, [loadContacts]);

  const filtered = contacts.filter((c) =>
    (type === 'todos' || c.type === type) &&
    (stage === 'todas' || c.stage === stage) &&
    (q === '' || `${c.name} ${c.company} ${c.email}`.toLowerCase().includes(q.toLowerCase()))
  );

  const leads = filtered.filter((c) => c.type === 'lead');
  const accounts = filtered.filter((c) => c.type === 'cliente');
  const getLeadProfile = (id) => leadProfilesById[id] || null;
  const totalMRR = accounts.reduce((sum, c) => sum + (c.mrr || 0), 0);
  const activeAccounts = accounts.filter((c) => c.stage === 'active').length;
  const riskAccounts = accounts.filter((c) => c.stage === 'risk').length;
  const avgLeadHealth = leads.length ? Math.round(leads.reduce((s, c) => s + (c.health || 0), 0) / leads.length) : 0;

  const formatEur = (n) => fmt('currency', n || 0);
  const fmtAgo = (h) => {
    if (h < 1) return t('time.minutes_ago');
    if (h < 24) return t('time.hours_ago', { n: h });
    return t('time.days_ago', { n: Math.floor(h / 24) });
  };
  const healthColor = (h) => (h >= 70 ? 'var(--ok)' : h >= 40 ? 'var(--warn)' : 'var(--bad)');

  const pushTimeline = async (contactId, item) => {
    setTimelineById((prev) => ({ ...prev, [contactId]: [item, ...(prev[contactId] || [])] }));
    try {
      await fetch(`/api/v1/crm/contacts/${contactId}/timeline`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() },
        body: JSON.stringify({ kind: item.kind || 'nota', by: item.by || 'Usuario', title: item.title || 'Nota', body: item.body || null }),
      });
    } catch (_) {}
  };

  const updateContact = async (contactId, patch) => {
    setContacts((prev) => prev.map((c) => (c.id === contactId ? { ...c, ...patch } : c)));
    setOpen((prev) => (prev && prev.id === contactId ? { ...prev, ...patch } : prev));
    const apiPatch = { ...patch };
    if ('type' in apiPatch) { apiPatch.contact_type = apiPatch.type; delete apiPatch.type; }
    if ('mrr' in apiPatch) { apiPatch.mrr_cents = Math.round((apiPatch.mrr || 0) * 100); delete apiPatch.mrr; }
    if ('arr' in apiPatch) { apiPatch.arr_cents = Math.round((apiPatch.arr || 0) * 100); delete apiPatch.arr; }
    try {
      await fetch(`/api/v1/crm/contacts/${contactId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() },
        body: JSON.stringify(apiPatch),
      });
    } catch (_) {}
  };

  const createContact = async () => {
    if (createSaving) return;
    setCreateError('');
    if (!draft.name.trim() || !draft.email.trim() || !draft.company.trim()) {
      notify(t('crm.required_fields'));
      setCreateError('Completa nombre, email y empresa.');
      return;
    }
    setCreateSaving(true);
    try {
      const res = await fetch('/api/v1/crm/contacts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() },
        body: JSON.stringify({
          name: draft.name.trim(),
          email: draft.email.trim(),
          company: draft.company.trim(),
          title: draft.title.trim() || null,
          phone: draft.phone.trim() || null,
          country: draft.country,
          owner_name: draft.ownerName,
          contact_type: draft.type,
          stage: draft.stage,
          mrr_cents: draft.type === 'cliente' ? 150000 : 0,
          arr_cents: draft.type === 'cliente' ? 1800000 : 0,
          health: 72,
        }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        const msg = d.detail || t('crm.error_create');
        notify(msg);
        setCreateError(msg);
        return;
      }
      setShowCreate(false);
      setCreateError('');
      setDraft({ name: '', email: '', company: '', title: '', phone: '', type: 'lead', stage: 'lead', country: 'España', ownerName: 'Admin' });
      await loadContacts();
      notify(t('crm.created'));
    } catch (_) {
      notify(t('crm.network_error'));
      setCreateError(t('crm.network_error'));
    } finally {
      setCreateSaving(false);
    }
  };

  const changeStage = (contactId, stageId) => {
    updateContact(contactId, { stage: stageId });
    pushTimeline(contactId, { t: Date.now(), kind: 'sistema', by: 'Sistema', title: t('crm.stage_updated'), body: t('crm.moved_to', { stage: stageId }) });
  };

  const onImportCsv = async (event) => {
    const file = event.target.files && event.target.files[0];
    if (!file) return;
    try {
      const text = await file.text();
      const lines = text.split(/\r?\n/).filter(Boolean);
      if (lines.length <= 1) return;
      const header = lines[0].split(',').map((x) => x.trim().toLowerCase());
      const idx = { name: header.indexOf('name'), email: header.indexOf('email'), company: header.indexOf('company'), title: header.indexOf('title') };
      if (idx.name < 0 || idx.email < 0 || idx.company < 0) {
        notify(t('crm.csv_invalid'));
        return;
      }
      for (const line of lines.slice(1)) {
        const cols = line.split(',').map((x) => x.trim());
        if (!cols[idx.name] || !cols[idx.email] || !cols[idx.company]) continue;
        await fetch('/api/v1/crm/contacts', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() },
          body: JSON.stringify({
            name: cols[idx.name],
            email: cols[idx.email],
            company: cols[idx.company],
            title: idx.title >= 0 ? cols[idx.title] : null,
            contact_type: 'lead',
            stage: 'lead',
          }),
        });
      }
      await loadContacts();
      notify(t('crm.csv_imported'));
    } catch (_) {
      notify(t('crm.csv_import_error'));
    } finally {
      event.target.value = '';
    }
  };

  const groupedByStage = D.stages.map((s) => ({ stage: s, items: leads.filter((c) => c.stage === s.id) }));
  const flatTimeline = Object.values(timelineById).flat().sort((a, b) => (b.t || 0) - (a.t || 0));

  const runLeadScoring = async () => {
    const targetLeads = leads.slice(0, 25);
    if (!targetLeads.length) {
      notify(t('crm.no_leads_to_score'));
      return;
    }
    let ok = 0;
    for (const lead of targetLeads) {
      try {
        const res = await fetch(`/api/v1/leads/${lead.id}/score`, {
          method: 'POST',
          headers: { Authorization: 'Bearer ' + getToken() },
        });
        if (res.ok) ok += 1;
      } catch (_) {}
    }
    notify(t('crm.scored_count', { n: ok }));
    await loadContacts();
  };

  const generateOutreachDrafts = async () => {
    const targetLeads = leads.slice(0, 15);
    if (!targetLeads.length) {
      notify(t('crm.no_leads_outreach'));
      return;
    }
    let ok = 0;
    for (const lead of targetLeads) {
      try {
        const res = await fetch(`/api/v1/leads/${lead.id}/outreach`, {
          method: 'POST',
          headers: { Authorization: 'Bearer ' + getToken() },
        });
        if (res.ok) ok += 1;
      } catch (_) {}
    }
    notify(t('crm.outreach_count', { n: ok }));
    await loadContacts();
  };

  const syncTwenty = async () => {
    try {
      const res = await fetch('/api/v1/leads/sync/twenty', {
        method: 'POST',
        headers: { Authorization: 'Bearer ' + getToken() },
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        notify((data.detail || 'sync error'));
        return;
      }
      notify(t('crm.synced_count', { synced: data.synced, skipped: data.skipped }));
    } catch (_) {
      notify(t('crm.sync_error'));
    }
  };

  const downloadCsvTemplate = () => {
    const csv = [
      'name,email,company,title,phone,country,owner_name',
      'Ana Perez,ana.perez@empresa.com,Empresa Uno,Directora Comercial,+34600000001,España,Admin',
      'Luis Gomez,luis.gomez@empresa.com,Empresa Dos,CEO,+34600000002,España,Admin',
    ].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'leads_import_template.csv';
    a.click();
    URL.revokeObjectURL(url);
    notify('Plantilla CSV descargada');
  };

  const moduleTabs = [
    { id: 'overview', label: t('crm.tab.overview') },
    { id: 'leads', label: lang === 'en' ? 'Leads' : 'Leads' },
    { id: 'accounts', label: t('crm.tab.accounts') },
    { id: 'pipeline', label: t('crm.tab.pipeline') },
    { id: 'activity', label: t('crm.tab.activity') },
    { id: 'automations', label: t('crm.tab.automations') },
  ];

  return (
    <div>
      <div className="page-head">
        <h1>{t('page.crm')}</h1>
        <span className="crumbs mono">{t('page.crm.crumbs')} <span>›</span> <span style={{ color: 'var(--ink)' }}>{t('page.crm.summary', { c: accounts.length, l: leads.length })}</span></span>
        <div className="actions">
          <input ref={fileRef} type="file" accept=".csv,text/csv" style={{ display: 'none' }} onChange={onImportCsv} />
          <button className="btn" onClick={downloadCsvTemplate}><Icon name="download" size={12} /> Plantilla CSV</button>
          <button className="btn" onClick={() => fileRef.current && fileRef.current.click()}><Icon name="upload" size={12} /> {t('btn.import_csv')}</button>
          <button className="btn" onClick={() => setShowCreate(true)}><Icon name="plus" size={12} /> {t('btn.new_contact')}</button>
        </div>
      </div>

      <div className="section">
        <div className="crm-kpi-row">
          <div className="crm-kpi"><div className="lbl">{t('crm.kpi.mrr')}</div><div className="val">{formatEur(totalMRR)}</div><div className="delta" style={{ color: 'var(--ok)' }}>{t('crm.delta.mom')}</div></div>
          <div className="crm-kpi"><div className="lbl">{t('crm.kpi.active')}</div><div className="val">{activeAccounts}</div><div className="delta" style={{ color: 'var(--ok)' }}>{t('crm.delta.month')}</div></div>
          <div className="crm-kpi"><div className="lbl">{t('crm.kpi.risk')}</div><div className="val">{riskAccounts}</div><div className="delta" style={{ color: 'var(--warn)' }}>{t('crm.delta.exposed', { v: formatEur(riskAccounts * 4200) })}</div></div>
          <div className="crm-kpi"><div className="lbl">{t('crm.kpi.leads')}</div><div className="val">{leads.length}</div><div className="delta" style={{ color: 'var(--info)' }}>{t('crm.delta.value', { v: formatEur(leads.length * 1800) })}</div></div>
          <div className="crm-kpi"><div className="lbl">{t('crm.kpi.lead_health')}</div><div className="val" style={{ color: healthColor(avgLeadHealth) }}>{avgLeadHealth}/100</div><div className="delta" style={{ color: 'var(--ink-3)' }}>{t('crm.kpi.auto_qualified')}</div></div>
        </div>

        <div className="crm-tabs" style={{ marginBottom: 12 }}>
          {moduleTabs.map((tab) => (
            <button key={tab.id} className={view === tab.id ? 'active' : ''} onClick={() => setView(tab.id)}>{tab.label}</button>
          ))}
        </div>

        <div className="crm-toolbar">
          <div className="crm-search">
            <Icon name="search" size={13} style={{ color: 'var(--ink-3)' }} />
            <input placeholder={t('crm.search')} value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
          {[['todos', t('crm.all')], ['cliente', t('crm.clients')], ['lead', t('crm.leads')]].map(([id, lbl]) => (
            <button key={id} className={'crm-pill' + (type === id ? ' active' : '')} onClick={() => setType(id)}>{lbl}</button>
          ))}
          <button className={'crm-pill' + (stage === 'todas' ? ' active' : '')} onClick={() => setStage('todas')}>{t('crm.all_stages')}</button>
          {D.stages.map((s) => (
            <button key={s.id} className={'crm-pill' + (stage === s.id ? ' active' : '')} onClick={() => setStage(s.id)}>
              <span className="dot" style={{ background: s.c }} />{s.label}
            </button>
          ))}
          <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)' }}>{t('crm.results', { n: filtered.length })}</span>
        </div>

        {loading && contacts.length === 0 && <div style={{ padding: '28px 0', textAlign: 'center', color: 'var(--ink-3)' }}>{t('crm.loading')}</div>}

        {view === 'overview' && (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="crm-table">
              <thead><tr><th>{t('crm.col.contact')}</th><th>{t('crm.col.company')}</th><th>{t('crm.col.stage')}</th><th>{t('crm.col.health')}</th><th>{t('crm.col.mrr')}</th><th>{t('crm.col.agent')}</th><th>{t('crm.col.last')}</th></tr></thead>
              <tbody>
                {filtered.slice(0, 80).map((c) => (
                  <tr key={c.id} onClick={() => setOpen(c)}>
                    <td><div className="crm-name-cell"><div className="av-c" style={{ background: '#ff5b1f' }}>{c.initials}</div><div><div className="nm">{c.name}</div><div className="sub">{c.title || '—'} · {c.email}</div></div></div></td>
                    <td><div style={{ fontWeight: 500 }}>{c.company}</div><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.country || '—'}</div></td>
                    <td onClick={(e) => e.stopPropagation()}><select className="select" value={c.stage} onChange={(e) => changeStage(c.id, e.target.value)} style={{ height: 28, minWidth: 130, padding: '0 8px', fontSize: 11.5, borderRadius: 999 }}>{D.stages.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}</select></td>
                    <td><div className="health-bar"><div className="track"><div className="fill" style={{ width: c.health + '%', background: healthColor(c.health) }} /></div><span className="health-num" style={{ color: healthColor(c.health) }}>{c.health}</span></div></td>
                    <td className="mono">{c.mrr ? formatEur(c.mrr) : '—'}</td>
                    <td>{c.assignedAgent || '—'}</td>
                    <td className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{fmtAgo(c.lastContactH)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {view === 'leads' && (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="crm-table">
              <thead><tr><th>{t('crm.col.contact')}</th><th>{t('crm.col.company')}</th><th>{t('crm.col.stage')}</th><th>{t('crm.col.qualification')}</th><th>{t('crm.col.next_action')}</th></tr></thead>
              <tbody>
                {leads.length === 0 && (
                  <tr>
                    <td colSpan={5} style={{ padding: '16px 14px', color: 'var(--ink-3)' }}>
                      No hay leads todavía. Empieza con `Nuevo contacto` o `Importar CSV` usando `Plantilla CSV`.
                    </td>
                  </tr>
                )}
                {leads.slice(0, 80).map((c) => {
                  const profile = getLeadProfile(c.id);
                  const qualification = profile?.qualification || (c.health >= 75 ? 'high' : c.health >= 50 ? 'medium' : 'low');
                  const nextStep = profile?.recommended_next_step || c.nextAction || '—';
                  const scoreValue = profile?.score ?? c.health;
                  return (
                  <tr key={c.id} onClick={() => setOpen(c)}>
                    <td>{c.name}<div className="sub">{c.email}</div></td>
                    <td>{c.company}<div className="sub">{c.title || '—'}</div></td>
                    <td>{c.stage}</td>
                    <td>
                      <span style={{ color: healthColor(scoreValue), fontWeight: 700 }}>
                        {qualification === 'hot' ? (lang === 'en' ? 'High' : 'Alta')
                          : qualification === 'warm' ? (lang === 'en' ? 'Medium' : 'Media')
                          : qualification === 'cold' ? (lang === 'en' ? 'Low' : 'Baja')
                          : `${scoreValue}/100`}
                      </span>
                    </td>
                    <td>{nextStep}</td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {view === 'accounts' && (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="crm-table">
              <thead><tr><th>{t('crm.col.contact')}</th><th>{t('crm.col.company')}</th><th>{t('crm.col.mrr')}</th><th>ARR</th><th>{t('crm.col.owner')}</th></tr></thead>
              <tbody>
                {accounts.slice(0, 80).map((c) => (
                  <tr key={c.id} onClick={() => setOpen(c)}>
                    <td>{c.name}<div className="sub">{c.email}</div></td>
                    <td>{c.company}</td>
                    <td className="mono">{formatEur(c.mrr || 0)}</td>
                    <td className="mono">{formatEur(c.arr || 0)}</td>
                    <td>{c.ownerName || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {view === 'pipeline' && (
          <div className="crm-kanban">
            {groupedByStage.map(({ stage: s, items }) => (
              <div key={s.id} className="crm-col">
                <div className="crm-col-head"><span className="dot" style={{ background: s.c }} /><span className="ttl">{s.label}</span><span className="ct">{items.length}</span></div>
                {items.slice(0, 10).map((c) => (
                  <div key={c.id} className="crm-card" onClick={() => setOpen(c)}>
                    <div className="crm-card-top"><div className="av-c" style={{ background: '#ff5b1f', width: 22, height: 22, fontSize: 9.5 }}>{c.initials}</div><div className="nm">{c.name}</div></div>
                    <div className="sub">{c.company} · {c.title || '—'}</div>
                    <div className="meta"><span style={{ color: healthColor(c.health) }}>● {c.health}</span><span>{fmtAgo(c.lastContactH)}</span></div>
                  </div>
                ))}
              </div>
            ))}
          </div>
        )}

        {view === 'activity' && (
          <div className="card" style={{ padding: '12px 16px' }}>
            {(flatTimeline.length ? flatTimeline : [{ id: 'empty', title: t('crm.empty_activity'), body: '—', by: 'Sistema', kind: 'sistema', t: Date.now() }]).slice(0, 80).map((ev, i) => (
              <div key={ev.id || i} className="tl-item" style={{ borderBottom: '1px dashed var(--line)' }}>
                <div className="tl-icon"><Icon name="pulse" size={13} /></div>
                <div className="tl-body">
                  <div className="top"><b>{ev.title}</b><span className="when" style={{ marginLeft: 'auto' }}>{fmtAgo(Math.max(0, Math.round((Date.now() - (ev.t || Date.now())) / 3600000)))}</span></div>
                  <div className="ln">{ev.body || '—'}</div>
                  <div className="by">{ev.by || 'Sistema'} · {ev.kind || 'nota'}</div>
                </div>
              </div>
            ))}
          </div>
        )}

        {view === 'automations' && (
          <div className="card" style={{ padding: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(260px,1fr))', gap: 12 }}>
              <div className="card" style={{ padding: 12 }}>
                <b>{t('crm.automation.lead_qualification')}</b>
                <p style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>{t('crm.automation.lead_qualification.desc')}</p>
                <button className="btn btn-sm" onClick={runLeadScoring}><Icon name="sparkles" size={11} /> {t('btn.run_scoring')}</button>
              </div>
              <div className="card" style={{ padding: 12 }}>
                <b>{t('crm.automation.outbound')}</b>
                <p style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>{t('crm.automation.outbound.desc')}</p>
                <button className="btn btn-sm" onClick={generateOutreachDrafts}><Icon name="chat" size={11} /> {t('btn.generate_drafts')}</button>
              </div>
              <div className="card" style={{ padding: 12 }}>
                <b>{t('crm.automation.sync')}</b>
                <p style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>{t('crm.automation.sync.desc')}</p>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <button className="btn btn-sm" onClick={syncTwenty}><Icon name="plug" size={11} /> {t('btn.sync_now')}</button>
                  <button className="btn btn-sm" onClick={() => window.dispatchEvent(new CustomEvent('af:navigate', { detail: 'integrations' }))}><Icon name="cog" size={11} /> {t('btn.configure')}</button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {showCreate && (
        <div className="crm-detail-back" onClick={(e) => { if (e.target === e.currentTarget) setShowCreate(false); }}>
          <div className="crm-detail" style={{ width: 520 }}>
            <div className="head"><div style={{ flex: 1 }}><h2>{t('btn.new_contact')}</h2><div className="sub">CRM</div></div><button className="btn btn-ghost" onClick={() => setShowCreate(false)}><Icon name="x" size={14} /></button></div>
            <div className="body" style={{ paddingTop: 10 }}>
              <div className="field-row"><div className="k">{t('crm.detail.name')}</div><div className="v"><input className="input" value={draft.name} onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))} /></div></div>
              <div className="field-row"><div className="k">{t('crm.detail.email')}</div><div className="v"><input className="input" value={draft.email} onChange={(e) => setDraft((d) => ({ ...d, email: e.target.value }))} /></div></div>
              <div className="field-row"><div className="k">{t('crm.detail.company')}</div><div className="v"><input className="input" value={draft.company} onChange={(e) => setDraft((d) => ({ ...d, company: e.target.value }))} /></div></div>
              <div className="field-row"><div className="k">{t('crm.detail.title')}</div><div className="v"><input className="input" value={draft.title} onChange={(e) => setDraft((d) => ({ ...d, title: e.target.value }))} /></div></div>
              <div className="field-row"><div className="k">{t('crm.detail.phone')}</div><div className="v"><input className="input" value={draft.phone} onChange={(e) => setDraft((d) => ({ ...d, phone: e.target.value }))} /></div></div>
              <div className="field-row"><div className="k">{t('crm.detail.type')}</div><div className="v"><select className="select" value={draft.type} onChange={(e) => setDraft((d) => ({ ...d, type: e.target.value, stage: e.target.value === 'cliente' ? 'active' : 'lead' }))}><option value="lead">Lead</option><option value="cliente">Cliente</option></select></div></div>
              {createError && (
                <div style={{ marginTop: 10, fontSize: 12, color: 'var(--bad)' }}>{createError}</div>
              )}
            </div>
            <div className="foot"><button className="btn" onClick={() => setShowCreate(false)} disabled={createSaving}>{t('btn.cancel')}</button><button className="btn btn-primary" onClick={createContact} disabled={createSaving}><Icon name="check" size={12} /> {createSaving ? 'Guardando...' : t('btn.create')}</button></div>
          </div>
        </div>
      )}

      {open && <ContactDrawer c={open} onClose={() => setOpen(null)} formatEur={formatEur} fmtAgo={fmtAgo} healthColor={healthColor} onChangeStage={changeStage} onLog={pushTimeline} />}
    </div>
  );
};

const ContactDrawer = ({ c, onClose, formatEur, fmtAgo, healthColor, onChangeStage, onLog }) => {
  const D = window.AF_CRM;
  const { t, lang } = useI18n();
  return (
    <>
      <div className="crm-detail-back" onClick={onClose} />
      <div className="crm-detail">
        <div className="head">
          <div className="av-l" style={{ background: '#ff5b1f' }}>{c.initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2>{c.name}</h2>
            <div className="sub">{c.title || '—'} · {c.company} · {c.email}</div>
          </div>
          <button className="btn btn-ghost" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>

        <div className="quick">
          <div><div className="lbl">MRR</div><div className="val">{c.mrr ? formatEur(c.mrr) : '—'}</div></div>
          <div><div className="lbl">Health</div><div className="val" style={{ color: healthColor(c.health) }}>{c.health}/100</div></div>
          <div><div className="lbl">ARR</div><div className="val">{c.arr ? formatEur(c.arr) : '—'}</div></div>
          <div><div className="lbl">Last</div><div className="val">{fmtAgo(c.lastContactH)}</div></div>
        </div>

        <div className="body">
          <div className="ttl"><span>{t('crm.detail.stage')}</span><span className="ln" /></div>
          <select className="select" value={c.stage} onChange={(e) => onChangeStage(c.id, e.target.value)} style={{ maxWidth: 220 }}>
            {D.stages.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>

          <div className="ttl"><span>{t('crm.tab.activity')}</span><span className="ln" /></div>
          <div className="tl-item">
            <div className="tl-icon"><Icon name="pulse" size={13} /></div>
            <div className="tl-body"><div className="top"><b>{t('crm.detail.last_update')}</b></div><div className="ln">{c.nextAction || '—'}</div></div>
          </div>
        </div>

        <div className="foot">
          <button className="btn" onClick={() => { onLog(c.id, { t: Date.now(), kind: 'email', by: 'Usuario', title: 'Email enviado', body: 'Contacto iniciado desde CRM' }); window.location.href = `mailto:${c.email}`; }}><Icon name="mail" size={12} /> Email</button>
          <button className="btn" onClick={() => { onLog(c.id, { t: Date.now(), kind: 'llamada', by: 'Usuario', title: 'Llamada', body: c.phone || 'Sin teléfono' }); if (c.phone) window.location.href = `tel:${c.phone}`; }}><Icon name="phone" size={12} /> {t('btn.call')}</button>
          <button className="btn btn-primary" onClick={() => { onLog(c.id, { t: Date.now(), kind: 'agente', by: 'Usuario', title: 'Asistente IA', body: 'Solicitud enviada a flujo comercial' }); window.afNotify && window.afNotify(t('crm.ai_workflow_requested')); }}><Icon name="sparkles" size={12} /> {t('btn.ask_agent')}</button>
        </div>
      </div>
    </>
  );
};

window.CRM = CRM;
