// HolidayScreen — Persian holiday/leave request form with calendar day picker.

const { useState: useStateH, useMemo: useMemoH } = React;

const faNumH = (n) => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);

const H_WEEKDAYS = ['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'];
const H_MONTHS = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور',
                  'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'];

const H_TODAY = 2;
const H_DAYS_IN_MONTH = 31;
const H_FIRST_OFFSET = 0;

const LEAVE_TYPES = [
  { id: 'personal',  label: 'استحقاقی' },
  { id: 'sick',      label: 'استعلاجی' },
  { id: 'unpaid',    label: 'بدون حقوق' },
];

// Pre-existing leave requests for the month (visual only)
const EXISTING_LEAVES = {
  7:  { status: 'approved' },   // approved leave on day 7
  14: { status: 'pending' },    // pending leave on day 14
};

function HolidayCalendar({ range, onPick }) {
  // range: { start: day | null, end: day | null }
  const cells = [];
  for (let i = 0; i < H_FIRST_OFFSET; i++) cells.push({ blank: true, key: `b${i}` });
  for (let d = 1; d <= H_DAYS_IN_MONTH; d++) cells.push({ day: d, key: `d${d}` });

  const { start, end } = range;
  const inRange = (d) => start && end && d >= Math.min(start, end) && d <= Math.max(start, end);
  const isEdge = (d) => d === start || d === end;

  return (
    <div style={{ padding: '0 14px' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
        gap: 2, marginBottom: 6,
      }}>
        {H_WEEKDAYS.map(w => (
          <div key={w} style={{
            textAlign: 'center', fontSize: 11, fontWeight: 600,
            color: 'var(--muted)', padding: '6px 0', letterSpacing: '0.04em',
          }}>{w}</div>
        ))}
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2,
      }}>
        {cells.map(c => {
          if (c.blank) return <div key={c.key} />;
          const isPast = c.day < H_TODAY;
          const isToday = c.day === H_TODAY;
          const existing = EXISTING_LEAVES[c.day];
          const edge = isEdge(c.day);
          const within = inRange(c.day);

          let bg = 'transparent';
          let fg = 'var(--ink)';
          let border = '1px solid transparent';

          if (edge) {
            bg = 'var(--accent)';
            fg = '#fff';
          } else if (within) {
            bg = 'color-mix(in oklab, var(--accent) 18%, transparent)';
            fg = 'var(--ink)';
          } else if (existing?.status === 'approved') {
            bg = 'color-mix(in oklab, var(--muted) 12%, transparent)';
            fg = 'var(--muted)';
          } else if (existing?.status === 'pending') {
            bg = 'color-mix(in oklab, var(--accent) 8%, transparent)';
            border = '1px dashed var(--accent)';
          } else if (isToday) {
            border = '1px solid var(--accent)';
          }

          if (isPast && !within && !edge) {
            fg = 'var(--muted)';
          }

          return (
            <button
              key={c.key}
              disabled={isPast || !!existing}
              onClick={() => onPick(c.day)}
              style={{
                all: 'unset',
                cursor: (isPast || existing) ? 'not-allowed' : 'pointer',
                aspectRatio: '1 / 1.05',
                borderRadius: 12,
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 3,
                background: bg, color: fg, border,
                opacity: (isPast && !within && !edge) ? 0.55 : 1,
                transition: 'background 160ms ease',
                position: 'relative',
              }}>
              <span style={{
                fontSize: 14, fontWeight: edge || isToday ? 700 : 500,
                fontVariantNumeric: 'tabular-nums',
              }}>{faNumH(c.day)}</span>
              {existing && !edge && !within && (
                <span style={{
                  fontSize: 8.5, fontWeight: 600,
                  color: existing.status === 'approved' ? 'var(--muted)' : 'var(--accent)',
                }}>{existing.status === 'approved' ? 'ثبت' : 'انتظار'}</span>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function HolidayScreen({ onBack, onSubmit }) {
  // selection: { start, end }
  const [range, setRange] = useStateH({ start: null, end: null });
  const [leaveType, setLeaveType] = useStateH('personal');
  const [reason, setReason] = useStateH('');
  const [submitted, setSubmitted] = useStateH(false);

  const handlePick = (day) => {
    setRange(r => {
      // no selection yet, or both set → start new
      if (!r.start || (r.start && r.end)) {
        return { start: day, end: null };
      }
      // start set, picking end
      if (day === r.start) return { start: null, end: null };
      return { start: Math.min(r.start, day), end: Math.max(r.start, day) };
    });
  };

  const dayCount = useMemoH(() => {
    if (!range.start) return 0;
    if (!range.end) return 1;
    return Math.abs(range.end - range.start) + 1;
  }, [range]);

  const rangeLabel = useMemoH(() => {
    if (!range.start) return null;
    if (!range.end) return `${faNumH(range.start)} خرداد`;
    return `${faNumH(range.start)} تا ${faNumH(range.end)} خرداد`;
  }, [range]);

  const canSubmit = !!range.start && !submitted;

  const handleSubmit = () => {
    if (!canSubmit) return;
    setSubmitted(true);
    const typeLabel = LEAVE_TYPES.find(t => t.id === leaveType)?.label;
    setTimeout(() => {
      onSubmit?.({ range, leaveType, reason, days: dayCount, label: `${typeLabel} · ${dayCount} روز` });
    }, 700);
  };

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)',
      height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 8px', flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          all: 'unset', cursor: 'pointer',
          width: 38, height: 38, borderRadius: 99,
          background: 'var(--surface)', border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink)',
        }}>
          <window.IconChevron size={16} dir="right" />
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>درخواست مرخصی</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>روز یا بازه را انتخاب کنید</div>
        </div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {/* month label */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '8px 24px 10px',
        }}>
          <button style={{ all: 'unset', cursor: 'pointer', padding: 6, color: 'var(--muted)' }}>
            <window.IconChevron size={16} dir="right" />
          </button>
          <div style={{ fontSize: 14, fontWeight: 600 }}>خرداد ۱۴۰۵</div>
          <button style={{ all: 'unset', cursor: 'pointer', padding: 6, color: 'var(--muted)' }}>
            <window.IconChevron size={16} dir="left" />
          </button>
        </div>

        <HolidayCalendar range={range} onPick={handlePick} />

        {/* legend */}
        <div style={{
          display: 'flex', gap: 14, padding: '12px 22px 4px',
          fontSize: 10.5, color: 'var(--muted)',
          flexWrap: 'wrap',
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 4, background: 'var(--accent)' }} /> انتخاب
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 4, background: 'color-mix(in oklab, var(--muted) 18%, transparent)' }} /> تایید شده
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 4, border: '1px dashed var(--accent)' }} /> در انتظار
          </span>
        </div>

        {/* leave type */}
        <div style={{ padding: '14px 18px 4px' }}>
          <div style={{
            fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
            marginBottom: 8, fontWeight: 500, padding: '0 2px',
          }}>نوع مرخصی</div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6,
          }}>
            {LEAVE_TYPES.map(t => {
              const active = t.id === leaveType;
              return (
                <button key={t.id}
                  onClick={() => setLeaveType(t.id)}
                  style={{
                    all: 'unset', cursor: 'pointer', textAlign: 'center',
                    padding: '10px 8px',
                    borderRadius: 12,
                    background: active ? 'var(--ink)' : 'var(--surface)',
                    color: active ? 'var(--bg)' : 'var(--ink)',
                    border: active ? '1px solid var(--ink)' : '1px solid var(--border)',
                    fontSize: 12.5, fontWeight: 600,
                    transition: 'all 160ms ease',
                  }}>{t.label}</button>
              );
            })}
          </div>
        </div>

        {/* reason */}
        <div style={{ padding: '14px 18px 14px' }}>
          <div style={{
            fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
            marginBottom: 8, fontWeight: 500, padding: '0 2px',
          }}>توضیحات (اختیاری)</div>
          <textarea
            value={reason}
            onChange={e => setReason(e.target.value)}
            placeholder="مثلاً: مراجعه به پزشک"
            style={{
              width: '100%', boxSizing: 'border-box',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 12,
              padding: '11px 12px',
              fontSize: 13, fontFamily: 'inherit',
              color: 'var(--ink)',
              resize: 'none', minHeight: 64,
              outline: 'none',
              direction: 'rtl',
            }}
          />
        </div>
      </div>

      {/* footer */}
      <div style={{
        flexShrink: 0,
        padding: '12px 18px 16px',
        background: 'var(--bg)',
        borderTop: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>
            {range.start ? rangeLabel : 'روزی انتخاب نشده'}
          </div>
          <div style={{
            fontSize: 18, fontWeight: 700,
            color: dayCount > 0 ? 'var(--accent)' : 'var(--ink)',
            lineHeight: 1.2,
          }}>
            {dayCount > 0 ? <>
              <span style={{
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                fontVariantNumeric: 'tabular-nums',
              }}>{faNumH(dayCount)}</span>
              <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--muted)' }}> روز</span>
            </> : <span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 500 }}>—</span>}
          </div>
        </div>
        <button
          disabled={!canSubmit}
          onClick={handleSubmit}
          style={{
            all: 'unset', cursor: canSubmit ? 'pointer' : 'not-allowed',
            padding: '13px 22px', borderRadius: 14,
            background: submitted
              ? 'color-mix(in oklab, var(--accent) 75%, #000)'
              : canSubmit ? 'var(--accent)' : 'var(--icon-bg)',
            color: !canSubmit && !submitted ? 'var(--muted)' : '#fff',
            fontSize: 14, fontWeight: 700,
            transition: 'background 180ms ease',
            minWidth: 110, textAlign: 'center',
          }}>
          {submitted ? '✓ ارسال شد' : 'ارسال درخواست'}
        </button>
      </div>
    </div>
  );
}

window.HolidayScreen = HolidayScreen;
