// ─── Shared: استایل‌ها و کامپوننت‌های مشترکِ صفحه‌ی قوانین ─────────────────────
// (قانونِ کاربر، ۲۰۲۶-۰۸-۱۹): این‌ها قبلاً توی هر ۶ تب جدا-جدا هاردکد شده بودن —
// حالا یه‌بار اینجا تعریف می‌شن و همه‌ی تب‌ها (که بعد از این فایل لود می‌شن، پس
// بهشون دسترسی دارن) ازشون استفاده می‌کنن.

// ── تبدیلِ میلادی↔شمسی — قانونِ کاربر (۲۰۲۶-۰۸-۲۴) ──────────────
// «period»یِ ماهانه (تارگت‌گذاری/آمارِ فروشنده) باید یه ماهِ شمسیِ کامل باشه (۱ تا ۲۹/۳۰/۳۱ام)،
// نه یه ماهِ میلادی با برچسبِ تقریبیِ شمسی — چون رويِ هم نمی‌افتن و گمراه‌کننده‌ست. بدونِ
// پیاده‌سازیِ دستیِ قواعدِ کبیسه‌یِ شمسی: از رويِ Intlِ خودِ مرورگر (که تقویمِ جلالی رو درست
// پیاده‌سازی کرده) روزبه‌روز جلو/عقب می‌ریم تا اولِ ماهِ شمسیِ موردنظر رو پیدا کنیم.
const JALALI_MONTHS = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
function jalaliParts(d) {
  const parts = new Intl.DateTimeFormat('en-US-u-ca-persian', { year: 'numeric', month: 'numeric', day: 'numeric' }).formatToParts(d);
  const get = t => parseInt(parts.find(p => p.type === t).value, 10);
  return { jy: get('year'), jm: get('month'), jd: get('day') };
}
// روزِ اولِ ماهِ شمسیِ (baseDate + monthOffset ماه) رو به‌صورتِ Date میلادی برمی‌گردونه
function jalaliMonthStartDate(baseDate, monthOffset) {
  const { jd } = jalaliParts(baseDate);
  let cur = new Date(baseDate);
  cur.setDate(cur.getDate() - (jd - 1)); // اول ماهِ شمسیِ همینِ الان
  if (monthOffset > 0) {
    for (let i = 0; i < monthOffset; i++) {
      const next = new Date(cur); next.setDate(next.getDate() + 31); // حتماً از ماهِ بعد رد می‌شه
      next.setDate(next.getDate() - (jalaliParts(next).jd - 1)); // اسنپ به اولِ همون ماه
      cur = next;
    }
  } else if (monthOffset < 0) {
    for (let i = 0; i < -monthOffset; i++) {
      const prev = new Date(cur); prev.setDate(prev.getDate() - 1); // یه روز می‌ره تو ماهِ قبل
      prev.setDate(prev.getDate() - (jalaliParts(prev).jd - 1)); // اسنپ به اولِ همون ماه
      cur = prev;
    }
  }
  return cur;
}
function jalaliMonthEndDate(monthStartDate) {
  const probe = new Date(monthStartDate); probe.setDate(probe.getDate() + 31); // حتماً می‌ره تو ماهِ بعد
  const p = jalaliParts(probe);
  const end = new Date(probe); end.setDate(end.getDate() - p.jd); // یه روز قبلِ اولِ ماهِ بعد = آخرِ همین ماه
  return end;
}
function jalaliMonthRange(baseDate, monthOffset) {
  const start = jalaliMonthStartDate(baseDate, monthOffset);
  const end   = jalaliMonthEndDate(start);
  const { jy, jm } = jalaliParts(start);
  return { start, end, jy, jm };
}

const RULES_INP = {
  padding: '6px 10px', borderRadius: 7, border: '1px solid rgba(255,255,255,0.1)',
  background: 'rgba(255,255,255,0.05)', color: '#e2e8f0', fontSize: 12, outline: 'none',
};

const RULES_CARD = {
  padding: '10px 14px', borderRadius: 9,
  background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.07)',
};

// سوئیچِ روشن/خاموشِ مشترک — اندازه‌هایی که تویِ کد قبلاً بودن: sm=قوانینِ ردیفی،
// md=تنظیماتِ تکی، lg=سوئیچِ حالتِ توزیع
const TOGGLE_SIZES = {
  sm: { w: 28, h: 16, dot: 10, pad: 3 },
  md: { w: 36, h: 20, dot: 14, pad: 3 },
  lg: { w: 44, h: 24, dot: 18, pad: 3 },
};

const Toggle = ({ on, onClick, size = 'sm', disabled, onColor = 'rgba(52,211,153,0.3)', onDot = '#34D399' }) => {
  const s = TOGGLE_SIZES[size] || TOGGLE_SIZES.sm;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: s.w, height: s.h, borderRadius: s.h / 2, padding: 0, border: 'none',
      cursor: disabled ? 'default' : 'pointer', flexShrink: 0, position: 'relative',
      background: on ? onColor : 'rgba(107,114,128,0.2)', transition: 'background 0.2s',
      opacity: disabled ? 0.5 : 1,
    }}>
      <div style={{
        width: s.dot, height: s.dot, borderRadius: '50%', position: 'absolute', top: s.pad,
        left: on ? s.w - s.dot - s.pad : s.pad, background: on ? onDot : '#6B7280', transition: 'left 0.2s',
      }} />
    </button>
  );
};

// هدرِ بخش — همون نوارِ «آیکون + عنوان + توضیحِ کوچیک + دکمه‌ی اختیاری» که تویِ
// هر ۶ تب تکرار شده بود
const SectionHeader = ({ icon, title, hint, action }) => (
  <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)', display: 'flex', alignItems: 'center', gap: 8 }}>
    {icon ? icon + ' ' : ''}{title}
    {hint && <span style={{ fontSize: 10, color: '#374151', fontWeight: 400 }}>{'— ' + hint}</span>}
    {action && <div style={{ marginRight: 'auto' }}>{action}</div>}
  </div>
);

// کارتِ تک‌ردیفیِ «عنوان + توضیح + سوئیچ» — یه الگویِ خیلی پرتکرار تویِ تنظیماتِ ساده
const ToggleRow = ({ title, hint, on, onClick, disabled, size = 'md' }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, ...RULES_CARD, marginBottom: 8 }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0' }}>{title}</div>
      {hint && <div style={{ fontSize: 11, color: '#475569', marginTop: 2 }}>{hint}</div>}
    </div>
    <Toggle on={on} onClick={onClick} disabled={disabled} size={size} />
    <span style={{ fontSize: 10, color: on ? '#34D399' : '#475569', width: 40 }}>{on ? 'فعال' : 'غیرفعال'}</span>
  </div>
);

// بخشِ جمع‌شونده — برایِ تب‌هایی که چند تنظیمِ نامرتبط رو زیرِ هم دارن، تا کاربر
// مجبور نباشه یه صفحه‌ی طولانی رو اسکرول کنه؛ پیش‌فرض باز (defaultOpen) هست چون
// همه‌ی این تنظیمات فعالن و کاربر باید در نگاهِ اول ببینتشون.
const CollapsibleSection = ({ icon, title, hint, defaultOpen = true, children }) => {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ borderRadius: 10, border: '1px solid rgba(99,102,241,0.2)', overflow: 'hidden', flexShrink: 0 }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px',
        background: 'rgba(99,102,241,0.07)', border: 'none', cursor: 'pointer', textAlign: 'right',
      }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: '#a5b4fc' }}>{icon ? icon + ' ' : ''}{title}</span>
        {hint && <span style={{ fontSize: 10, color: '#64748b', fontWeight: 400 }}>{'— ' + hint}</span>}
        <span style={{ marginRight: 'auto', fontSize: 11, color: '#64748b' }}>{open ? '▲' : '▼'}</span>
      </button>
      {open && <div style={{ padding: 14 }}>{children}</div>}
    </div>
  );
};

// ─── Shared: RulesRow ──────────────────────────────────────────────────────
// props: rule, type ('ops'|'eval'), headers, load, toast, setEditing

const RulesRow = ({ rule, type, headers, load, toast, setEditing }) => {
  const active  = type === 'eval' ? rule.enabled : rule.is_active;
  const valDisp = rule.value_type === 'boolean'
    ? (rule.value === 'true' ? '✅ بله' : '❌ خیر')
    : (rule.value + (rule.unit ? ' ' + rule.unit : ''));
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 9,
      background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.07)',
      opacity: active ? 1 : 0.45, transition: 'opacity 0.15s',
    }}>
      <button
        onClick={() => {
          const updated = type === 'eval'
            ? { ...rule, enabled: rule.enabled ? 0 : 1 }
            : { ...rule, is_active: rule.is_active ? 0 : 1 };
          const url  = type === 'eval'
            ? `/api/distrules/evaluation/rules/${rule.rule_key}`
            : `/api/distrules/rules/${rule.id}`;
          const body = type === 'eval'
            ? { enabled: updated.enabled }
            : { is_active: updated.is_active };
          fetch(url, { method: 'PUT', headers, body: JSON.stringify(body) })
            .then(r => r.json()).then(d => { if (d.success) load(); else toast('خطا', 'error'); });
        }}
        style={{
          width: 28, height: 16, borderRadius: 8, padding: 0, border: 'none', cursor: 'pointer', flexShrink: 0,
          background: active ? 'rgba(52,211,153,0.3)' : 'rgba(107,114,128,0.2)',
          position: 'relative', transition: 'background 0.2s',
        }}>
        <div style={{
          width: 10, height: 10, borderRadius: '50%', position: 'absolute', top: 3,
          left: active ? 14 : 4, background: active ? '#34D399' : '#6B7280', transition: 'left 0.2s',
        }} />
      </button>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0' }}>{rule.label || rule.name}</div>
        {rule.description && <div style={{ fontSize: 10, color: '#475569', marginTop: 2, lineHeight: 1.5 }}>{rule.description}</div>}
      </div>

      <div style={{ fontSize: 12, fontWeight: 700, color: active ? '#38BDF8' : '#374151', flexShrink: 0, whiteSpace: 'nowrap' }}>
        {valDisp}
      </div>

      <button onClick={() => setEditing({ rule: { ...rule }, type })} style={{
        padding: '4px 10px', borderRadius: 7, fontSize: 11, cursor: 'pointer', flexShrink: 0,
        border: '1px solid rgba(99,102,241,0.25)', background: 'rgba(99,102,241,0.08)', color: '#818CF8',
      }}>
        {'ویرایش'}
      </button>
    </div>
  );
};
