const SELLER_REPORT_DEST_META = {
  telegram:     { label: 'شناسه عددی (chat_id) مقصد — یوزرنیم کار نمی‌کند، از دستور /chatid در ربات بگیرید', placeholder: 'مثلاً 123456789' },
  bale:         { label: 'شناسه عددی (chat_id) مقصد — یوزرنیم کار نمی‌کند، از دستور /chatid در ربات بگیرید', placeholder: 'مثلاً 123456789' },
  email:        { label: 'آدرس ایمیل مقصد — مثلاً واحد مالی',      placeholder: 'مثلاً finance@company.com' },
  google_sheet: { label: 'شناسه اسپردشیت گوگل (Spreadsheet ID)',   placeholder: 'مثلاً 1AbCdEfGhIjKlMnOpQrStUvWxYz' },
};

// ─── تنظیمات گزارش روزانه اکسل کارتابل فروش (خود فروشنده) ───────────
const SellerReportSettings = ({ seller }) => {
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
  const { useToast } = window.SB_UI;
  const toast = useToast();

  const [hour, setHour] = React.useState('');
  const [platform, setPlatform] = React.useState('telegram');
  const [platformId, setPlatformId] = React.useState('');
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [sending, setSending] = React.useState(false);

  React.useEffect(() => {
    fetch('/api/seller/me', { headers }).then(r => r.json())
      .then(d => {
        if (d.success) {
          const s = d.data.seller;
          setHour(s.report_hour || '');
          setPlatform(s.report_platform || 'telegram');
          setPlatformId(s.report_platform_id || '');
        }
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const save = () => {
    if (hour && !/^([01]\d|2[0-3]):[0-5]\d$/.test(hour)) {
      toast('فرمت ساعت باید HH:MM باشد', 'error');
      return;
    }
    setSaving(true);
    fetch('/api/seller/report-settings', {
      method: 'PUT', headers,
      body: JSON.stringify({ report_hour: hour || null, report_platform: platform, report_platform_id: platformId || null }),
    })
      .then(r => r.json())
      .then(d => {
        setSaving(false);
        if (d.success) toast('تنظیمات گزارش ذخیره شد', 'success');
        else toast(d.error || 'خطا در ذخیره', 'error');
      })
      .catch(() => { setSaving(false); toast('خطا در ارتباط با سرور', 'error'); });
  };

  const sendNow = () => {
    if (!platformId) {
      toast('اول شناسه (chat_id) مقصد را وارد و ذخیره کن', 'error');
      return;
    }
    setSending(true);
    fetch('/api/seller/send-report', { method: 'POST', headers })
      .then(r => r.json())
      .then(d => {
        setSending(false);
        if (d.success) toast('گزارش امروز ارسال شد', 'success');
        else toast(d.error || 'خطا در ارسال گزارش', 'error');
      })
      .catch(() => { setSending(false); toast('خطا در ارتباط با سرور', 'error'); });
  };

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 300, color: 'rgba(255,255,255,.3)', fontFamily: 'Vazirmatn' }}>در حال بارگذاری…</div>
  );

  const inputStyle = {
    width: '100%', padding: '9px 12px', borderRadius: 8,
    background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)',
    color: '#e2e8f0', fontSize: 13, outline: 'none', boxSizing: 'border-box',
  };

  return (
    <div style={{ padding: 24, maxWidth: 480, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
        <span style={{ fontSize: 22 }}>📊</span>
        <span style={{ fontSize: 18, fontWeight: 800, color: '#fff' }}>گزارش روزانه کارتابل فروش</span>
      </div>
      <div style={{ fontSize: 12, color: 'rgba(255,255,255,.4)', marginBottom: 20, lineHeight: 1.8 }}>
        اگر ساعت زیر را تنظیم کنی، هر روز در همان ساعت یک فایل اکسل از فعالیت‌ها و فروش‌های آن روز تو به کانال و مقصدی که مشخص می‌کنی (مثلاً واحد مالی) ارسال می‌شود.
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, background: 'rgba(255,255,255,.04)', border: '1px solid rgba(255,255,255,.07)', borderRadius: 14, padding: 20 }}>
        <div>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>ساعت ارسال (خالی = غیرفعال)</div>
          <input type="time" value={hour} onChange={e => setHour(e.target.value)} title="ساعت ارسال گزارش" placeholder="HH:MM" style={{ ...inputStyle, direction: 'ltr' }} />
        </div>
        <div>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>کانال ارسال</div>
          <select value={platform} onChange={e => setPlatform(e.target.value)} title="کانال ارسال گزارش" style={inputStyle}>
            <option value="telegram">تلگرام</option>
            <option value="bale">بله</option>
            <option value="email">ایمیل</option>
            <option value="google_sheet">گوگل‌شیت</option>
          </select>
        </div>
        <div>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>{SELLER_REPORT_DEST_META[platform].label}</div>
          <input type="text" value={platformId} onChange={e => setPlatformId(e.target.value)} placeholder={SELLER_REPORT_DEST_META[platform].placeholder}
            style={{ ...inputStyle, direction: 'ltr' }} />
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
          <button onClick={save} disabled={saving}
            style={{ flex: 1, padding: '9px 18px', borderRadius: 8, fontSize: 13, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>
            {saving ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
          </button>
          <button onClick={sendNow} disabled={sending}
            style={{ flex: 1, padding: '9px 18px', borderRadius: 8, fontSize: 13, cursor: 'pointer', border: '1px solid rgba(52,211,153,.35)', background: 'rgba(52,211,153,.1)', color: '#34D399', fontWeight: 600 }}>
            {sending ? 'در حال ارسال...' : '📤 ارسال گزارش امروز الان'}
          </button>
        </div>
      </div>
    </div>
  );
};

window.SellerReportSettings = SellerReportSettings;
