// Saraya Events -- Bilingual smart-translation helper for vendor listing forms.
//
// Speeds up bilingual (EN/AR) listing entry for vendors. Reusable across the
// Add/Edit Product, Add/Edit Rental, Add/Edit Service forms (all share
// ListingFormModal in vendor-dashboard.jsx) and the Vendor Business Profile
// editor (VendorProfileEditor). This file only renders UI controls and talks
// to the 'translate-text' Supabase Edge Function -- it never calls a
// translation provider directly and never holds an API key client-side.
//
// Rules this helper always follows:
//   - Translation is optional and never blocks manual entry or submission.
//   - Translated text is never locked -- the vendor can edit it immediately.
//   - If the target field already has content, the vendor must confirm
//     before it gets replaced.
//   - Errors are shown inline with a clear retry-or-type-manually message.

/* Calls the translate-text edge function. Always resolves (never throws) so
   callers don't need try/catch -- check res.ok. */
function sarayaTranslateText(text, targetLang) {
  const db = window.SarayaDB;
  if (!db || !window.supabaseConfigured) {
    return Promise.resolve({ ok: false, error: 'not_configured' });
  }
  return db.functions.invoke('translate-text', { body: { text, targetLang } })
    .then(({ data, error }) => {
      if (error) return { ok: false, error: 'network_error' };
      if (!data) return { ok: false, error: 'empty_response' };
      return data;
    })
    .catch(() => ({ ok: false, error: 'network_error' }));
}

/* Small reusable disclosure note required next to every translate control. */
function TranslateNote({ ar }) {
  return (
    <p style={{ fontSize: 11.5, color: 'var(--fg-muted)', margin: '2px 0 0', lineHeight: 1.4 }}>
      {ar ? 'الترجمة تلقائية. يرجى المراجعة قبل النشر.' : 'Translation is auto-generated. Please review before publishing.'}
    </p>
  );
}
window.TranslateNote = TranslateNote;

/* Renders "Auto-fill English from Arabic" / "Auto-fill Arabic from English"
   buttons for one EN/AR field pair. Never locks the field -- it just calls
   onSetEn/onSetAr once, same as if the vendor had typed the result. Confirms
   before overwriting existing target text.

   Props:
     enValue, arValue   current field values
     onSetEn, onSetAr   setters, called with the translated string
     ar                 current UI language (for button/label wording)
     dense              optional, tightens spacing for narrow mobile layouts */
function TranslateFieldControls({ enValue, arValue, onSetEn, onSetAr, ar, dense }) {
  const [busy, setBusy] = React.useState(null); // 'en' | 'ar' | null
  const [err, setErr] = React.useState('');
  const [confirmDir, setConfirmDir] = React.useState(null); // 'toEn' | 'toAr' | null

  const run = async (dir, skipConfirm) => {
    setErr('');
    const toEn = dir === 'toEn';
    const source = toEn ? arValue : enValue;
    const targetHasText = toEn ? !!(enValue && enValue.trim()) : !!(arValue && arValue.trim());

    if (!source || !source.trim()) {
      setErr(toEn
        ? (ar ? 'أدخل نصاً بالعربية أولاً.' : 'Enter Arabic text first.')
        : (ar ? 'أدخل نصاً بالإنجليزية أولاً.' : 'Enter English text first.'));
      return;
    }
    if (targetHasText && !skipConfirm) {
      setConfirmDir(dir);
      return;
    }
    setConfirmDir(null);
    setBusy(toEn ? 'en' : 'ar');
    const res = await sarayaTranslateText(source, toEn ? 'en' : 'ar');
    setBusy(null);
    if (!res.ok) {
      setErr(res.error === 'not_configured'
        ? (ar ? 'خدمة الترجمة غير متاحة حالياً. يرجى إدخال النص يدوياً.' : 'Translation service is unavailable right now. Please enter text manually.')
        : (ar ? 'فشلت الترجمة. حاول مرة أخرى أو أدخل النص يدوياً.' : 'Translation failed. Please try again or enter text manually.'));
      return;
    }
    if (toEn) onSetEn(res.translated); else onSetAr(res.translated);
  };

  const btnStyle = (active) => ({
    fontSize: dense ? 12 : 12.5,
    padding: dense ? '5px 10px' : '6px 12px',
    borderRadius: 20,
    border: '1px solid var(--gold-deep)',
    background: 'var(--white)',
    color: 'var(--gold-deep)',
    cursor: busy ? 'default' : 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    gap: 6,
    fontWeight: 500,
    opacity: busy !== null && !active ? 0.5 : 1,
    whiteSpace: 'nowrap',
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, gridColumn: '1 / -1', margin: dense ? '2px 0 6px' : '4px 0 8px' }}>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <button type="button" onClick={() => run('toEn')} disabled={busy !== null} style={btnStyle(busy === 'en')}>
          <Icon name="sparkles" size={13} />
          {busy === 'en' ? (ar ? 'جارٍ الترجمة…' : 'Translating…') : (ar ? 'ملء الإنجليزية من العربية' : 'Auto-fill English from Arabic')}
        </button>
        <button type="button" onClick={() => run('toAr')} disabled={busy !== null} style={btnStyle(busy === 'ar')}>
          <Icon name="sparkles" size={13} />
          {busy === 'ar' ? (ar ? 'جارٍ الترجمة…' : 'Translating…') : (ar ? 'ملء العربية من الإنجليزية' : 'Auto-fill Arabic from English')}
        </button>
      </div>

      {confirmDir && (
        <div style={{ fontSize: 12.5, background: 'var(--cream)', border: '1px solid var(--line-strong)', borderRadius: 8, padding: '9px 11px', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <span>{ar ? 'سيتم استبدال النص المترجم الحالي. متابعة؟' : 'This will replace the existing translated text. Continue?'}</span>
          <button type="button" onClick={() => run(confirmDir, true)} style={{ fontSize: 12, fontWeight: 600, color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
            {ar ? 'نعم، استبدال' : 'Yes, replace'}
          </button>
          <button type="button" onClick={() => setConfirmDir(null)} style={{ fontSize: 12, color: 'var(--fg-secondary)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
            {ar ? 'إلغاء' : 'Cancel'}
          </button>
        </div>
      )}

      {err && <p style={{ fontSize: 12, color: 'var(--error, #dc2626)', margin: 0 }}>{err}</p>}

      <TranslateNote ar={ar} />
    </div>
  );
}
window.TranslateFieldControls = TranslateFieldControls;
