// DateTimePicker — Persian (Jalali) calendar and time picker.
// Exposed as window.PersianDatePicker and window.PersianTimePicker.

// Jalali utilities from window.JalaliUtils (utils.js — R12 dedup)
const { _toJalali, _toGregorian, _jDays, _toIso, _fromIso, _jn: _n, _pwIdx, J_MONTHS, J_WDAYS: J_DAYS } = window.JalaliUtils;

// ── Styles ──────────────────────────────────────────────────────────
const dpS = {
  calWrap: {
    background: 'var(--surface)', borderRadius: 14,
    border: '1px solid var(--c-border-xs)',
    direction: 'rtl', userSelect: 'none', overflow: 'hidden',
  },
  calHead: {
    display: 'flex', alignItems: 'center',
    padding: '10px 12px',
    borderBottom: '1px solid var(--c-border-xs)',
  },
  navBtn: {
    width: 32, height: 32, borderRadius: 999,
    background: 'transparent', border: 'none', cursor: 'pointer',
    color: 'var(--ink-2)', display: 'grid', placeItems: 'center',
  },
  monthLbl: {
    flex: 1, textAlign: 'center',
    font: "600 13px 'Estedad', sans-serif", color: 'var(--ink)',
  },
  grid: {
    display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
    gap: 2, padding: '6px 8px 10px',
  },
  wdHead: {
    textAlign: 'center', padding: '2px 0 5px',
    font: "500 11px 'Estedad', sans-serif", color: 'var(--ink-3)',
  },
  day: {
    height: 34, width: '100%', display: 'grid', placeItems: 'center',
    borderRadius: 8, background: 'transparent', border: 'none', cursor: 'pointer',
    font: "500 13px 'Estedad', sans-serif", color: 'var(--ink)',
    transition: 'background 80ms',
  },
  dayToday:    { background: 'var(--firoozeh-soft)', color: 'var(--firoozeh-deep)' },
  daySelected: { background: 'var(--firoozeh)', color: '#fff' },

  timeWrap: {
    background: 'var(--surface)', borderRadius: 14,
    border: '1px solid var(--c-border-xs)',
    direction: 'rtl', userSelect: 'none', overflow: 'hidden',
    marginTop: 10,
  },
  timeHead: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '12px 16px 0',
  },
  timeLbl: { font: "500 13px 'Estedad', sans-serif", color: 'var(--ink-2)' },
  timeBody: {
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: '10px 16px 6px',
  },
  spinCol: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 },
  spinBtn: {
    background: 'transparent', border: 'none', cursor: 'pointer',
    color: 'var(--ink-2)', padding: '4px 12px',
    display: 'grid', placeItems: 'center', borderRadius: 8,
  },
  spinVal: {
    font: "700 30px/1 'Estedad', sans-serif",
    color: 'var(--ink)', width: 60, textAlign: 'center',
  },
  timeSep: {
    font: "700 28px/1 'Estedad', sans-serif",
    color: 'var(--ink-3)', padding: '0 4px', marginBottom: 4,
  },
  periodLbl: {
    textAlign: 'center', padding: '2px 0 12px',
    font: "500 12px 'Estedad', sans-serif", color: 'var(--firoozeh-deep)',
  },
  disabled: { height: 14 },
};

// ── PersianDatePicker ────────────────────────────────────────────────
function PersianDatePicker({ value, onChange }) {
  const { Icons } = window;

  const todayArr = (() => { const n = new Date(); return _toJalali(n.getFullYear(), n.getMonth()+1, n.getDate()); })();
  const selArr   = value ? _toJalali(..._fromIso(value)) : null;

  const [viewY, setViewY] = React.useState(() => (selArr || todayArr)[0]);
  const [viewM, setViewM] = React.useState(() => (selArr || todayArr)[1]);

  // Sync view when value changes externally (e.g. quick-chip click)
  React.useEffect(() => {
    if (value) {
      const [jy, jm] = _toJalali(..._fromIso(value));
      setViewY(jy); setViewM(jm);
    }
  }, [value]);

  const prevMonth = () => viewM === 1  ? (setViewY(y => y-1), setViewM(12)) : setViewM(m => m-1);
  const nextMonth = () => viewM === 12 ? (setViewY(y => y+1), setViewM(1))  : setViewM(m => m+1);

  const firstDate = (() => { const [gy, gm, gd] = _toGregorian(viewY, viewM, 1); return new Date(gy, gm-1, gd); })();
  const offset    = _pwIdx(firstDate.getDay());
  const total     = _jDays(viewY, viewM);

  const cells = [...Array(offset).fill(null), ...Array.from({length: total}, (_, i) => i+1)];

  const isSel   = d => selArr   && selArr[0]===viewY   && selArr[1]===viewM   && selArr[2]===d;
  const isToday = d => todayArr[0]===viewY && todayArr[1]===viewM && todayArr[2]===d;

  return (
    <div style={dpS.calWrap}>
      <div style={dpS.calHead}>
        {/* RTL: left=next, right=prev */}
        <button style={dpS.navBtn} onClick={nextMonth} aria-label="ماه بعد"><Icons.ChevLeft size={15} /></button>
        <span style={dpS.monthLbl}>{J_MONTHS[viewM-1]} {_n(viewY)}</span>
        <button style={dpS.navBtn} onClick={prevMonth} aria-label="ماه قبل"><Icons.Chev size={15} /></button>
      </div>
      <div style={dpS.grid}>
        {J_DAYS.map(w => <div key={w} style={dpS.wdHead}>{w}</div>)}
        {cells.map((d, i) => d === null ? <div key={`_${i}`} /> : (
          <button key={d}
            style={{ ...dpS.day, ...(isSel(d) ? dpS.daySelected : isToday(d) ? dpS.dayToday : {}) }}
            onClick={() => onChange(_toIso(..._toGregorian(viewY, viewM, d)))}
          >
            {_n(d)}
          </button>
        ))}
      </div>
    </div>
  );
}

// ── PersianTimePicker ────────────────────────────────────────────────
function PersianTimePicker({ value, onChange }) {
  const { Icons } = window;
  const [on, setOn]     = React.useState(!!value);
  const [h,  setH]      = React.useState(() => value ? parseInt(value.split(':')[0], 10) : 9);
  const [m,  setM]      = React.useState(() => value ? Math.round(parseInt(value.split(':')[1], 10) / 15) * 15 % 60 : 0);

  const emit = (enabled, hour, min) => {
    onChange(enabled ? `${String(hour).padStart(2,'0')}:${String(min).padStart(2,'0')}` : '');
  };

  const toggle = () => { const next = !on; setOn(next); emit(next, h, m); };
  const adjH   = d => { const nh = (h + d + 24) % 24; setH(nh); emit(on, nh, m); };
  const adjM   = d => { const nm = (m + d + 60) % 60; setM(nm); emit(on, h, nm); };

  const period = h < 5 ? 'بامداد' : h < 12 ? 'صبح' : h === 12 ? 'ظهر' : h < 17 ? 'بعدازظهر' : 'شب';

  return (
    <div style={dpS.timeWrap}>
      <div style={dpS.timeHead}>
        <span style={dpS.timeLbl}>ساعت</span>
        <button
          aria-label="فعال"
          onClick={toggle}
          style={{
            width: 42, height: 24, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: on ? 'var(--firoozeh)' : 'var(--ink-4)',
            position: 'relative', direction: 'ltr',
            transition: 'background 150ms', flexShrink: 0,
          }}
        >
          <span style={{
            position: 'absolute', top: 3,
            left: on ? 21 : 3,
            width: 18, height: 18, borderRadius: '50%',
            background: '#fff', transition: 'left 150ms',
            display: 'block',
          }} />
        </button>
      </div>

      {on ? (
        <>
          <div style={dpS.timeBody}>
            <div style={dpS.spinCol}>
              <button style={dpS.spinBtn} onClick={() => adjH(1)}>
                <Icons.ChevDown size={18} style={{ transform: 'rotate(180deg)' }} />
              </button>
              <span style={dpS.spinVal}>{_n(String(h).padStart(2,'0'))}</span>
              <button style={dpS.spinBtn} onClick={() => adjH(-1)}>
                <Icons.ChevDown size={18} />
              </button>
            </div>
            <span style={dpS.timeSep}>:</span>
            <div style={dpS.spinCol}>
              <button style={dpS.spinBtn} onClick={() => adjM(15)}>
                <Icons.ChevDown size={18} style={{ transform: 'rotate(180deg)' }} />
              </button>
              <span style={dpS.spinVal}>{_n(String(m).padStart(2,'0'))}</span>
              <button style={dpS.spinBtn} onClick={() => adjM(-15)}>
                <Icons.ChevDown size={18} />
              </button>
            </div>
          </div>
          <div style={dpS.periodLbl}>{period}</div>
        </>
      ) : (
        <div style={dpS.disabled} />
      )}
    </div>
  );
}

window.PersianDatePicker = PersianDatePicker;
window.PersianTimePicker = PersianTimePicker;
