// ============================
// LELUSA — Editor de Plantillas de Correo
// src/pages/admin-email-editor.jsx
//
// Editor HTML/CSS por plantilla con sistema de {{variables}}, panel de
// variables clickeables y vista previa en vivo lado a lado.
// Lee/escribe la tabla email_templates en Supabase.
// ============================

(function () {
  const { useState, useEffect, useRef, useCallback } = React;

  const getClient = () => {
    const cfg = window.LELUSA_SUPABASE || {};
    if (!cfg.url || !cfg.anonKey || !window.supabase?.createClient) return null;
    return window.supabase.createClient(cfg.url, cfg.anonKey);
  };

  const SYSTEM_KEYS = ['booking', 'approval', 'reminder', 'internal-notification', 'manual'];

  function EmailTemplateEditor() {
    const { t } = window.ReactI18next.useTranslation();
    const TE = window.LelusaEmailTemplates;

    const [templates, setTemplates] = useState([]);
    const [activeKey, setActiveKey] = useState(null);
    const [draft, setDraft] = useState(null); // { key, name, subject, html, is_system, enabled }
    const [dirty, setDirty] = useState(false);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const htmlRef = useRef(null);

    const loadTemplates = useCallback(async () => {
      setLoading(true);
      const client = getClient();
      if (!client) { setLoading(false); return; }
      const { data } = await client.from('email_templates').select('*').order('is_system', { ascending: false }).order('name');
      const rows = data || [];
      setTemplates(rows);
      if (rows.length && !activeKey) {
        setActiveKey(rows[0].key);
        setDraft({ ...rows[0] });
      }
      setLoading(false);
    }, [activeKey]);

    useEffect(() => { loadTemplates(); }, []);

    const selectTemplate = (tpl) => {
      if (dirty && !window.confirm(t('admin_email_editor_unsaved') + ' ¿Continuar?')) return;
      setActiveKey(tpl.key);
      setDraft({ ...tpl });
      setDirty(false);
    };

    const updateDraft = (patch) => {
      setDraft(d => ({ ...d, ...patch }));
      setDirty(true);
    };

    // Inserta texto en la posición del cursor del textarea de HTML.
    const insertAtCursor = (text) => {
      const el = htmlRef.current;
      if (!el) { updateDraft({ html: (draft.html || '') + text }); return; }
      const start = el.selectionStart, end = el.selectionEnd;
      const val = draft.html || '';
      const next = val.slice(0, start) + text + val.slice(end);
      updateDraft({ html: next });
      requestAnimationFrame(() => {
        el.focus();
        el.selectionStart = el.selectionEnd = start + text.length;
      });
    };

    const handleSave = async () => {
      if (!draft) return;
      const client = getClient();
      if (!client) { alert(t('admin_email_editor_no_supabase')); return; }
      setSaving(true);
      const payload = {
        key: draft.key,
        name: draft.name || draft.key,
        subject: draft.subject || '',
        html: draft.html || '',
        is_system: !!draft.is_system,
        enabled: draft.enabled !== false,
      };
      const { error } = await client.from('email_templates').upsert(payload, { onConflict: 'key' });
      setSaving(false);
      if (error) { alert('Error: ' + error.message); return; }
      setDirty(false);
      await loadTemplates();
      alert(t('admin_email_editor_saved'));
    };

    const handleNew = async () => {
      const name = window.prompt(t('admin_email_editor_new_name_prompt'));
      if (!name) return;
      const base = name.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
      const slug = 'custom-' + (base || 'tpl') + '-' + Date.now().toString(36).slice(-4);
      const fresh = { key: slug, name, subject: name, html: TE.brandSkeleton(), is_system: false, enabled: true };
      const client = getClient();
      if (client) await client.from('email_templates').upsert(fresh, { onConflict: 'key' });
      await loadTemplates();
      setActiveKey(slug);
      setDraft(fresh);
      setDirty(false);
    };

    const handleDelete = async () => {
      if (!draft || draft.is_system) return;
      if (!window.confirm(t('admin_email_editor_delete_confirm'))) return;
      const client = getClient();
      if (client) await client.from('email_templates').delete().eq('key', draft.key);
      setActiveKey(null);
      setDraft(null);
      setDirty(false);
      await loadTemplates();
    };

    const handleInsertBrand = () => {
      if (!window.confirm(t('admin_email_editor_insert_brand_confirm'))) return;
      updateDraft({ html: TE.brandSkeleton() });
    };

    const handleSendTest = async () => {
      const email = window.prompt(t('admin_email_test_prompt'));
      if (!email) return;
      // Guardar primero para que la Edge Function lea la versión actual.
      if (dirty) await handleSave();
      const sample = TE.getSampleData(draft.key);
      const res = await window.LelusaEmail.sendEmail(draft.key, email, sample);
      alert(res?.ok ? t('admin_email_test_success') : (t('admin_email_error_prefix') + (res?.error || '')));
    };

    if (loading) {
      return <div style={{ padding: 32, textAlign: 'center', color: 'var(--muted)' }}>{t('admin_email_editor_loading')}</div>;
    }
    if (!getClient()) {
      return <div style={{ padding: 32, textAlign: 'center', color: 'var(--muted)' }}>{t('admin_email_editor_no_supabase')}</div>;
    }

    const vars = draft ? TE.getVarsForTemplate(draft.key) : { specific: [], global: [] };
    const previewHtml = draft ? renderPreview(TE, draft) : '';

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Lista de plantillas */}
        <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 16, padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <h3 style={{ margin: 0, fontSize: 14, fontWeight: 900, color: 'var(--text)' }}>{t('admin_email_editor_list_title')}</h3>
            <button onClick={handleNew} style={pillBtn(true)}>+ {t('admin_email_editor_new')}</button>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {templates.map(tpl => (
              <button key={tpl.key} onClick={() => selectTemplate(tpl)} style={chipStyle(tpl.key === activeKey)}>
                {tpl.name}
                <span style={{ marginLeft: 6, fontSize: 9, opacity: 0.7, textTransform: 'uppercase' }}>
                  {tpl.is_system ? t('admin_email_editor_system') : t('admin_email_editor_custom')}
                </span>
              </button>
            ))}
          </div>
        </div>

        {draft && (
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 16, alignItems: 'start' }} className="lel-tpl-grid">
            {/* Columna izquierda: edición */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 16, padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
                <Field label={t('admin_email_editor_field_name')}>
                  <input value={draft.name || ''} onChange={e => updateDraft({ name: e.target.value })} style={inputStyle} />
                </Field>
                <Field label={t('admin_email_editor_field_subject')}>
                  <input value={draft.subject || ''} onChange={e => updateDraft({ subject: e.target.value })} style={inputStyle} />
                </Field>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={draft.enabled !== false} onChange={e => updateDraft({ enabled: e.target.checked })} style={{ width: 18, height: 18, accentColor: 'var(--primary)' }} />
                  {t('admin_email_editor_enabled')}
                </label>
              </div>

              {/* Panel de variables */}
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 16, padding: 16 }}>
                <h4 style={{ margin: '0 0 4px', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_email_editor_vars_title')}</h4>
                <p style={{ margin: '0 0 12px', fontSize: 11, color: 'var(--muted)' }}>{t('admin_email_editor_vars_hint')}</p>
                {vars.specific.length > 0 && (
                  <>
                    <div style={varGroupLabel}>{t('admin_email_editor_vars_specific')}</div>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
                      {vars.specific.map(v => (
                        <button key={v.key} title={v.label} onClick={() => insertAtCursor('{{' + v.key + '}}')} style={varChip('var(--primary)')}>
                          {'{{' + v.key + '}}'}
                        </button>
                      ))}
                    </div>
                  </>
                )}
                <div style={varGroupLabel}>{t('admin_email_editor_vars_global')}</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {vars.global.map(v => (
                    <button key={v.key} title={v.label} onClick={() => insertAtCursor('{{' + v.key + '}}')} style={varChip('var(--sage-dark)')}>
                      {'{{' + v.key + '}}'}
                    </button>
                  ))}
                </div>
              </div>

              {/* Editor HTML */}
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 16, padding: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <label style={{ fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_email_editor_field_html')}</label>
                  <button onClick={handleInsertBrand} style={pillBtn(false)}>{t('admin_email_editor_insert_brand')}</button>
                </div>
                <textarea
                  ref={htmlRef}
                  value={draft.html || ''}
                  onChange={e => updateDraft({ html: e.target.value })}
                  spellCheck={false}
                  style={{
                    width: '100%', minHeight: 380, padding: 12, border: '1px solid var(--border)', borderRadius: 10,
                    fontFamily: "'SFMono-Regular', Consolas, 'Liberation Mono', monospace", fontSize: 12, lineHeight: 1.5,
                    background: '#FBF7F3', color: 'var(--text)', resize: 'vertical', outline: 'none', whiteSpace: 'pre',
                  }}
                />
              </div>

              {/* Acciones */}
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                <button onClick={handleSave} disabled={saving} style={{ ...primaryBtn, flex: 1, opacity: saving ? 0.6 : 1 }}>
                  {saving ? t('admin_email_editor_saving') : t('admin_email_editor_save')}
                </button>
                <button onClick={handleSendTest} style={ghostBtn}>{t('admin_email_editor_send_test')}</button>
                {!draft.is_system && (
                  <button onClick={handleDelete} style={{ ...ghostBtn, color: '#C83A3A', borderColor: '#F0C4C4' }}>{t('admin_email_editor_delete')}</button>
                )}
              </div>
              {dirty && <div style={{ fontSize: 11, color: 'var(--primary-dark)', fontWeight: 600 }}>● {t('admin_email_editor_unsaved')}</div>}
            </div>

            {/* Columna derecha: preview en vivo */}
            <div style={{ position: 'sticky', top: 16, minWidth: 0 }}>
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 16, padding: 16 }}>
                <h4 style={{ margin: '0 0 12px', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_email_editor_preview')}</h4>
                <div style={{ border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden', background: '#fff' }}>
                  <iframe srcDoc={previewHtml} title="preview" style={{ width: '100%', height: 620, border: 'none', display: 'block' }} />
                </div>
              </div>
            </div>
          </div>
        )}

        <style>{`@media (max-width: 900px){ .lel-tpl-grid{ grid-template-columns: 1fr !important; } }`}</style>
      </div>
    );
  }

  // Render de preview: reemplaza variables con datos de ejemplo.
  function renderPreview(TE, draft) {
    const sample = TE.getSampleData(draft.key);
    // signature como sample contiene \n; convertir para que se vea en preview.
    const data = { ...sample, signature: (sample.signature || '').replace(/\n/g, '<br>') };
    return TE.renderTemplate(draft.html || '', data);
  }

  // --- estilos ---
  const inputStyle = { width: '100%', padding: 12, border: '1px solid var(--border)', borderRadius: 10, fontSize: 13, background: 'var(--bg-soft)', outline: 'none', color: 'var(--text)' };
  const primaryBtn = { padding: '12px 20px', border: 'none', borderRadius: 999, background: 'var(--primary)', color: '#fff', fontWeight: 700, fontSize: 14, cursor: 'pointer' };
  const ghostBtn = { padding: '12px 18px', border: '1px solid var(--border)', borderRadius: 999, background: 'transparent', color: 'var(--text)', fontWeight: 600, fontSize: 13, cursor: 'pointer' };
  const varGroupLabel = { fontSize: 10, fontWeight: 800, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 6 };

  const pillBtn = (filled) => ({
    padding: '6px 12px', borderRadius: 999, fontSize: 12, fontWeight: 700, cursor: 'pointer',
    border: filled ? 'none' : '1px solid var(--border)',
    background: filled ? 'var(--primary)' : 'transparent',
    color: filled ? '#fff' : 'var(--text)',
  });
  const chipStyle = (active) => ({
    padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 600, cursor: 'pointer',
    border: '1px solid ' + (active ? 'var(--primary)' : 'var(--border)'),
    background: active ? 'var(--primary)' : 'var(--bg-soft)',
    color: active ? '#fff' : 'var(--text)',
  });
  const varChip = (color) => ({
    padding: '5px 10px', borderRadius: 8, fontSize: 11, cursor: 'pointer',
    border: '1px solid var(--border)', background: 'var(--bg-soft)', color,
    fontFamily: "'SFMono-Regular', Consolas, monospace", fontWeight: 600,
  });

  function Field({ label, children }) {
    return (
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text)' }}>{label}</span>
        {children}
      </label>
    );
  }

  window.EmailTemplateEditor = EmailTemplateEditor;
})();
