// ============================
// LELUSA — Admin Email Panel
// src/pages/admin-email.jsx
// ============================

(function () {
  const PageLayout = window.AdminMobileLayout || window.AdminLayout || (({ title, children }) => (
    <div style={{ minHeight: '100vh', background: 'var(--bg-soft)', padding: 24 }}>
      <h1 style={{ margin: '0 0 18px', color: 'var(--text)' }}>{title}</h1>
      {children}
    </div>
  ));
  const Button = window.Btn || (({ children, onClick, disabled, style = {} }) => (
    <button type="button" onClick={onClick} disabled={disabled} style={style}>{children}</button>
  ));
  const Icon = window.Icon || (() => null);
  const EMAIL_DEFAULTS = {
    from_name: 'Lelusa',
    internal_enabled: false,
    toggles: {
      booking: false,
      approval: false,
      reminder: false,
      internal: {},
    },
    overrides: {
      signature: '',
    },
  };

  const normalizeEmailSettings = (settings) => ({
    ...EMAIL_DEFAULTS,
    ...(settings || {}),
    toggles: {
      ...EMAIL_DEFAULTS.toggles,
      ...(settings?.toggles || {}),
      internal: {
        ...EMAIL_DEFAULTS.toggles.internal,
        ...(settings?.toggles?.internal || {}),
      },
    },
    overrides: {
      ...EMAIL_DEFAULTS.overrides,
      ...(settings?.overrides || {}),
    },
  });

  function Card({ title, children }) {
    return (
      <section style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 18, padding: 18, boxShadow: '0 10px 30px rgba(58,42,32,0.05)' }}>
        {title && <h3 style={{ margin: '0 0 14px', fontSize: 14, fontWeight: 900, color: 'var(--text)', fontFamily: "'DM Sans', sans-serif" }}>{title}</h3>}
        {children}
      </section>
    );
  }

  function Input({ label, value = '', onChange, placeholder = '' }) {
    return (
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text)' }}>{label}</span>
        <input value={value || ''} onChange={onChange} placeholder={placeholder} style={window.ADMIN_INPUT_STYLE || { width: '100%', padding: 12, border: '1px solid var(--border)', borderRadius: 10 }} />
      </label>
    );
  }

  function EmptyState({ message }) {
    return (
      <div style={{ border: '1px dashed var(--border)', borderRadius: 14, padding: 24, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>
        {message}
      </div>
    );
  }

  const getEmailApi = () => {
    if (window.LelusaEmail?.sendEmail && window.LelusaEmail?.previewEmail) return window.LelusaEmail;
    return null;
  };

  function AdminEmailPage() {
    const { t } = window.ReactI18next.useTranslation();
    const [activeTab, setActiveTab] = React.useState('compose');
    const { useBusinessData } = window.LelusaStore;
    const data = useBusinessData();
    const [settings, setSettings] = React.useState(null);
    const [logs, setLogs] = React.useState([]);
    const [loading, setLoading] = React.useState(true);

    // Form states
    const [manualEmail, setManualEmail] = React.useState({ to: '', subject: '', message: '' });
    const [previewHtml, setPreviewHtml] = React.useState('');
    const [isSending, setIsSending] = React.useState(false);

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

    const loadData = async () => {
      setLoading(true);
      const cfg = window.LELUSA_SUPABASE || {};
      if (!cfg.url) {
        setSettings(normalizeEmailSettings(null));
        setLoading(false);
        return;
      }
      const client = window.supabase.createClient(cfg.url, cfg.anonKey);
      
      const [settingsRes, logsRes] = await Promise.all([
        client.from('email_settings').select('*').single(),
        client.from('email_log').select('*').order('created_at', { ascending: false }).limit(50)
      ]);

      setSettings(normalizeEmailSettings(settingsRes.data));
      if (logsRes.data) setLogs(logsRes.data);
      setLoading(false);
    };

    const handleSendManual = async () => {
      if (!manualEmail.to || !manualEmail.subject || !manualEmail.message) return;
      const emailApi = getEmailApi();
      if (!emailApi) {
        alert(t('admin_email_error_prefix') + 'Modulo de email no disponible.');
        return;
      }
      setIsSending(true);
      const res = await emailApi.sendEmail('manual', manualEmail.to, {
        subject: manualEmail.subject,
        message: manualEmail.message
      });
      setIsSending(false);
      if (res.ok) {
        alert(t('admin_email_sent_success'));
        setManualEmail({ to: '', subject: '', message: '' });
        loadData();
      } else {
        alert(t('admin_email_error_prefix') + res.error);
      }
    };

    const handlePreview = async () => {
      const emailApi = getEmailApi();
      if (!emailApi) {
        alert(t('admin_email_error_prefix') + 'Modulo de email no disponible.');
        return;
      }
      const res = await emailApi.previewEmail('manual', {
        subject: manualEmail.subject,
        message: manualEmail.message
      });
      if (res.html) setPreviewHtml(res.html);
    };

    const updateToggles = async (newToggles) => {
      const cfg = window.LELUSA_SUPABASE;
      const updated = { ...settings, toggles: newToggles };
      setSettings(updated);
      if (!cfg?.url || !settings) return;
      const client = window.supabase.createClient(cfg.url, cfg.anonKey);
      await client.from('email_settings').update({ toggles: newToggles }).eq('id', 1);
    };

    const updateOverrides = async (newOverrides) => {
      const cfg = window.LELUSA_SUPABASE;
      const updated = { ...settings, overrides: newOverrides };
      setSettings(updated);
      if (!cfg?.url || !settings) return;
      const client = window.supabase.createClient(cfg.url, cfg.anonKey);
      await client.from('email_settings').update({ overrides: newOverrides }).eq('id', 1);
    };

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

    return (
      <PageLayout title={t('admin_email_page_title')}>
        <div style={{ display: 'flex', gap: '8px', overflowX: 'auto', padding: '16px', background: 'var(--card)', borderBottom: '1px solid var(--border)', position: 'sticky', top: 0, zIndex: 10 }}>
          <TabBtn active={activeTab === 'compose'} onClick={() => setActiveTab('compose')}>{t('admin_email_tab_compose')}</TabBtn>
          <TabBtn active={activeTab === 'templates'} onClick={() => setActiveTab('templates')}>{t('admin_email_tab_templates')}</TabBtn>
          <TabBtn active={activeTab === 'editor'} onClick={() => setActiveTab('editor')}>{t('admin_email_tab_editor')}</TabBtn>
          <TabBtn active={activeTab === 'history'} onClick={() => setActiveTab('history')}>{t('admin_email_tab_history')}</TabBtn>
          <TabBtn active={activeTab === 'config'} onClick={() => setActiveTab('config')}>{t('admin_email_tab_config')}</TabBtn>
        </div>

        <div style={{ padding: '24px 24px 100px', display: 'flex', flexDirection: 'column', gap: '24px' }}>
          {activeTab === 'compose' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              <Card title={t('admin_email_compose_title')}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                  <Input
                    label={t('admin_email_field_to')}
                    placeholder={t('admin_email_field_to_ph')}
                    value={manualEmail.to}
                    onChange={e => setManualEmail({...manualEmail, to: e.target.value})}
                  />
                  <Input
                    label={t('admin_email_field_subject')}
                    placeholder={t('admin_email_field_subject_ph')}
                    value={manualEmail.subject}
                    onChange={e => setManualEmail({...manualEmail, subject: e.target.value})}
                  />
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
                    <label style={{ fontSize: '12px', fontWeight: 700, color: 'var(--text)' }}>{t('admin_email_field_message')}</label>
                    <textarea
                      style={{ width: '100%', padding: '12px', border: '1px solid var(--border)', borderRadius: '10px', minHeight: '150px', fontSize: '13px', fontFamily: "'DM Sans', sans-serif", outline: 'none', background: 'var(--bg-soft)' }}
                      placeholder={t('admin_email_field_message_ph')}
                      value={manualEmail.message}
                      onChange={e => setManualEmail({...manualEmail, message: e.target.value})}
                    />
                  </div>
                  <div style={{ display: 'flex', gap: '10px' }}>
                    <Button variant="ghost" onClick={handlePreview} style={{ flex: 1 }}>{t('admin_email_btn_preview')}</Button>
                    <Button onClick={handleSendManual} disabled={isSending} style={{ flex: 1 }}>{isSending ? t('admin_email_btn_sending') : t('admin_email_btn_send')}</Button>
                  </div>
                </div>
              </Card>

              {previewHtml && (
                <Card title={t('admin_email_preview_title')}>
                  <div style={{ border: '1px solid var(--border)', borderRadius: '12px', overflow: 'hidden', background: '#fff' }}>
                    <iframe
                      srcDoc={previewHtml}
                      style={{ width: '100%', height: '500px', border: 'none' }}
                      title="Email Preview"
                    />
                  </div>
                  <Button variant="ghost" onClick={() => setPreviewHtml('')} style={{ marginTop: '12px', width: '100%' }}>{t('admin_email_btn_close_preview')}</Button>
                </Card>
              )}
            </div>
          )}

          {activeTab === 'templates' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
              <Card title={t('admin_email_templates_clients_title')}>
                <TemplateRow
                  label={t('admin_email_template_booking')}
                  active={settings?.toggles?.booking}
                  onChange={v => updateToggles({...settings.toggles, booking: v})}
                />
                <TemplateRow
                  label={t('admin_email_template_approval')}
                  active={settings?.toggles?.approval}
                  onChange={v => updateToggles({...settings.toggles, approval: v})}
                />
                <TemplateRow
                  label={t('admin_email_template_reminder')}
                  active={settings?.toggles?.reminder}
                  onChange={v => updateToggles({...settings.toggles, reminder: v})}
                />
              </Card>

              <Card title={t('admin_email_templates_internal_title')}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '16px', borderBottom: '1px solid var(--border)' }}>
                  <span style={{ fontWeight: 600, fontSize: '14px' }}>{t('admin_email_global_mirror')}</span>
                  <input 
                    type="checkbox" 
                    style={{ width: '20px', height: '20px', accentColor: 'var(--primary)' }}
                    checked={settings?.internal_enabled}
                    onChange={e => {
                      const cfg = window.LELUSA_SUPABASE;
                      if (!cfg?.url || !settings) {
                        setSettings(normalizeEmailSettings({ ...settings, internal_enabled: e.target.checked }));
                        return;
                      }
                      const client = window.supabase.createClient(cfg.url, cfg.anonKey);
                      setSettings({...settings, internal_enabled: e.target.checked});
                      client.from('email_settings').update({ internal_enabled: e.target.checked }).eq('id', 1);
                    }}
                  />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                  {Object.entries(settings?.toggles?.internal || {}).map(([key, val]) => (
                    <label key={key} style={{ display: 'flex', alignItems: 'center', gap: '10px', fontSize: '13px', cursor: 'pointer', textTransform: 'capitalize' }}>
                      <input 
                        type="checkbox" 
                        style={{ width: '18px', height: '18px', accentColor: 'var(--primary)' }}
                        checked={val} 
                        onChange={e => {
                          const next = {...settings.toggles.internal, [key]: e.target.checked};
                          updateToggles({...settings.toggles, internal: next});
                        }}
                      />
                      {key}
                    </label>
                  ))}
                </div>
              </Card>

              <Card title={t('admin_email_brand_title')}>
                <Input
                  label={t('admin_email_field_from_name')}
                  value={settings?.from_name}
                  onChange={e => {
                    const cfg = window.LELUSA_SUPABASE;
                    if (!cfg?.url || !settings) {
                      setSettings(normalizeEmailSettings({ ...settings, from_name: e.target.value }));
                      return;
                    }
                    const client = window.supabase.createClient(cfg.url, cfg.anonKey);
                    setSettings({...settings, from_name: e.target.value});
                    client.from('email_settings').update({ from_name: e.target.value }).eq('id', 1);
                  }}
                />
                <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', marginTop: '16px' }}>
                  <label style={{ fontSize: '12px', fontWeight: 700, color: 'var(--text)' }}>{t('admin_email_field_signature')}</label>
                  <textarea 
                    style={{ width: '100%', padding: '12px', border: '1px solid var(--border)', borderRadius: '10px', minHeight: '80px', fontSize: '13px', fontFamily: "'DM Sans', sans-serif", outline: 'none', background: 'var(--bg-soft)' }}
                    value={settings?.overrides?.signature}
                    onChange={e => updateOverrides({...settings.overrides, signature: e.target.value})}
                  />
                </div>
              </Card>
            </div>
          )}

          {activeTab === 'editor' && (
            window.EmailTemplateEditor
              ? <window.EmailTemplateEditor />
              : <EmptyState message="Editor no disponible." />
          )}

          {activeTab === 'history' && (
            <Card title={t('admin_email_history_title')}>
              {logs.length === 0 ? (
                <EmptyState message={t('admin_email_history_empty')} />
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  {logs.map(log => (
                    <div key={log.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px', border: '1px solid var(--border)', borderRadius: '12px', background: 'var(--card)' }}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: '14px', fontWeight: 600, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{log.to_email}</div>
                        <div style={{ fontSize: '11px', color: 'var(--muted)', marginTop: '2px' }}>{log.subject} • {new Date(log.created_at).toLocaleString()}</div>
                      </div>
                      <div style={{ marginLeft: '12px' }}>
                        <span style={{ display: 'inline-block', padding: '3px 8px', borderRadius: '999px', fontSize: '10px', fontWeight: 700, textTransform: 'uppercase', background: log.status === 'sent' ? '#DCF5E6' : '#FFE0E0', color: log.status === 'sent' ? '#2A8A50' : '#C83A3A' }}>
                          {window.LelusaStatusLabel(log.status)}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          )}

          {activeTab === 'config' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              <Card title={t('admin_email_config_resend_title')}>
                <p style={{ fontSize: '13px', color: 'var(--muted)', lineHeight: 1.6, marginBottom: '16px' }}>
                  {t('admin_email_config_resend_desc', { user: 'SMTP_USER', pass: 'SMTP_PASS' })}
                </p>
                <Button variant="ghost" style={{ width: '100%' }} onClick={() => window.open('https://supabase.com/dashboard', '_blank')}>
                  {t('admin_email_config_dashboard_btn')}
                </Button>
              </Card>

              <Card title={t('admin_email_test_title')}>
                <Button style={{ width: '100%' }} onClick={async () => {
                  const email = prompt(t('admin_email_test_prompt'));
                  if (!email) return;
                  const emailApi = getEmailApi();
                  if (!emailApi) {
                    alert(t('admin_email_error_prefix') + 'Modulo de email no disponible.');
                    return;
                  }
                  const res = await emailApi.sendEmail('manual', email, {
                    subject: t('admin_email_test_subject'),
                    message: t('admin_email_test_message')
                  });
                  alert(res.ok ? t('admin_email_test_success') : t('admin_email_error_prefix') + res.error);
                  loadData();
                }}>
                  {t('admin_email_test_btn')}
                </Button>
              </Card>
            </div>
          )}
        </div>
      </PageLayout>
    );
  }

  function TabBtn({ children, active, onClick }) {
    return (
      <button 
        onClick={onClick}
        style={{
          padding: '8px 16px', borderRadius: '999px', fontSize: '13px', fontWeight: 600,
          whiteSpace: 'nowrap', transition: 'all 0.2s', border: 'none', cursor: 'pointer',
          background: active ? 'var(--primary)' : 'var(--bg-soft)',
          color: active ? '#fff' : 'var(--muted)',
        }}
      >
        {children}
      </button>
    );
  }

  function TemplateRow({ label, active, onChange }) {
    const { t } = window.ReactI18next.useTranslation();
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
        <span style={{ fontSize: '14px', color: 'var(--text)' }}>{label}</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <span style={{ fontSize: '11px', fontWeight: 600, color: active ? '#2A8A50' : 'var(--light)' }}>
            {active ? t('admin_email_status_active') : t('admin_email_status_inactive')}
          </span>
          <input 
            type="checkbox" 
            style={{ width: '18px', height: '18px', accentColor: 'var(--primary)', cursor: 'pointer' }}
            checked={active} 
            onChange={e => onChange(e.target.checked)} 
          />
        </div>
      </div>
    );
  }

  window.AdminEmailPage = AdminEmailPage;
})();
