// CalendarScreen — User work calendar showing assigned stores per day, with agreed price.

const { useState: useStateCal, useMemo: useMemoCal } = React;

const PERSIAN_MONTHS = [
  'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور',
  'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند',
];

const WEEKDAYS = ['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'];
const DAYS_IN_MONTH = 31;
const FIRST_DAY_OFFSET = 0;

const statusColor = (s) => ({
  done:     'var(--muted)',
  today:    'var(--accent)',
  pending:  'var(--danger)',
  upcoming: 'var(--ink)',
}[s] || 'var(--ink)');

const statusLabel = (s) => ({
  done:     'انجام شد',
  today:    'امروز',
  pending:  'انجام نشده',
  upcoming: 'پیش‌رو',
}[s] || '');

function MonthGrid({ selected, onSelect, today, assignments }) {
  const cells = [];
  for (let i = 0; i < FIRST_DAY_OFFSET; i++) cells.push({ blank: true, key: `b${i}` });
  for (let d = 1; d <= DAYS_IN_MONTH; d++) cells.push({ day: d, key: `d${d}` });

  return (
    <div style={{ padding: '0 14px' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
        gap: 2, marginBottom: 6,
      }}>
        {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 visits = assignments[c.day] || [];
          const isToday = c.day === today;
          const isSelected = c.day === selected;
          const isPast = c.day < today;
          const hasVisits = visits.length > 0;

          return (
            <button
              key={c.key}
              onClick={() => onSelect(c.day)}
              style={{
                all: 'unset', cursor: 'pointer',
                aspectRatio: '1 / 1.05',
                borderRadius: 12,
                position: 'relative',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 4,
                background: isSelected
                  ? 'var(--ink)'
                  : isToday
                    ? 'color-mix(in oklab, var(--accent) 14%, transparent)'
                    : 'transparent',
                color: isSelected
                  ? 'var(--bg)'
                  : isPast && !isToday
                    ? 'var(--muted)'
                    : 'var(--ink)',
                border: isToday && !isSelected ? '1px solid var(--accent)' : '1px solid transparent',
                transition: 'background 160ms ease',
              }}>
              <span style={{
                fontSize: 14, fontWeight: isToday || isSelected ? 700 : 500,
                fontVariantNumeric: 'tabular-nums',
              }}>{window.faNumS(c.day)}</span>
              {hasVisits && (
                <div style={{ display: 'flex', gap: 2 }}>
                  {visits.slice(0, 3).map((v, i) => (
                    <span key={i} style={{
                      width: 4, height: 4, borderRadius: 99,
                      background: isSelected ? 'var(--bg)' : statusColor(v.status),
                      opacity: isSelected ? 0.7 : 1,
                    }} />
                  ))}
                </div>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function VisitList({ day, visits }) {
  if (!visits || visits.length === 0) {
    return (
      <div style={{
        margin: '4px 18px 18px',
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 16, padding: '24px 16px', textAlign: 'center',
      }}>
        <div style={{ fontSize: 13, color: 'var(--muted)' }}>
          برای روز {window.faNumS(day)} خرداد فروشگاهی ثبت نشده است
        </div>
      </div>
    );
  }
  const dayTotal = visits.reduce((acc, v) => {
    const s = window.getStoreById(v.storeId);
    return acc + (s?.price || 0);
  }, 0);

  return (
    <div style={{ padding: '4px 18px 22px' }}>
      <div style={{
        fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
        marginBottom: 10, fontWeight: 500,
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      }}>
        <span>{window.faNumS(day)} خرداد · {window.faNumS(visits.length)} فروشگاه</span>
        <span style={{
          color: 'var(--accent)', fontWeight: 700, fontSize: 12,
        }}>{window.fmtToman(dayTotal)}</span>
      </div>
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 16, overflow: 'hidden',
      }}>
        {visits.map((v, i) => {
          const store = window.getStoreById(v.storeId);
          if (!store) return null;
          return (
            <div key={i} style={{
              padding: '12px 14px',
              borderTop: i ? '1px solid var(--border)' : 'none',
              display: 'flex', alignItems: 'flex-start', gap: 12,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: 'var(--icon-bg)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: statusColor(v.status), flexShrink: 0, marginTop: 2,
              }}>
                <window.IconPin size={18} color="currentColor" />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
                  gap: 8, marginBottom: 3,
                }}>
                  <div style={{
                    fontSize: 14, fontWeight: 600, color: 'var(--ink)',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>{store.name}</div>
                </div>
                <div style={{
                  fontSize: 11.5, color: 'var(--muted)',
                  display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6,
                }}>
                  <span>{store.addr}</span>
                  <span style={{ opacity: 0.5 }}>•</span>
                  <span style={{
                    fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                    fontVariantNumeric: 'tabular-nums',
                  }}>{v.time}</span>
                </div>
                {store.open && store.close && (
                  <div style={{
                    fontSize: 11, color: 'var(--muted)',
                    display: 'flex', alignItems: 'center', gap: 5, marginBottom: 6,
                  }}>
                    <window.IconClock size={13} color="currentColor" />
                    <span>ساعت کاری:</span>
                    <span style={{
                      fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                      fontVariantNumeric: 'tabular-nums', color: 'var(--ink)', fontWeight: 600,
                    }}>{store.open} تا {store.close}</span>
                  </div>
                )}
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  gap: 8,
                }}>
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    fontSize: 11, color: 'var(--accent)', fontWeight: 700,
                    background: 'color-mix(in oklab, var(--accent) 10%, transparent)',
                    padding: '3px 8px', borderRadius: 99,
                  }}>
                    <span style={{
                      fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                      fontVariantNumeric: 'tabular-nums',
                    }}>{window.fmtToman(store.price)}</span>
                  </div>
                  <div style={{
                    fontSize: 10.5, fontWeight: 600,
                    padding: '3px 9px', borderRadius: 99,
                    background: v.status === 'today'
                      ? 'color-mix(in oklab, var(--accent) 14%, transparent)'
                      : 'var(--icon-bg)',
                    color: statusColor(v.status),
                    whiteSpace: 'nowrap',
                  }}>{statusLabel(v.status)}</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function CalendarScreen({ onBack }) {
  const store = window.useAppStore();
  const userId = store.currentUserId;
  const assignments = store.assignments[userId] || {};
  const [selected, setSelected] = useStateCal(store.today);
  const visits = assignments[selected];

  const summary = useMemoCal(() => {
    let total = 0, done = 0, today = 0, upcoming = 0;
    Object.values(assignments).forEach(arr => {
      arr.forEach(v => {
        total++;
        if (v.status === 'done') done++;
        else if (v.status === 'today') today++;
        else if (v.status === 'upcoming') upcoming++;
      });
    });
    return { total, done, today, upcoming };
  }, [assignments]);

  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',
    }}>
      <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' }}>
        <div style={{ display: 'flex', gap: 8, padding: '8px 18px 14px' }}>
          {[
            { label: 'انجام شد', value: summary.done, color: 'var(--muted)' },
            { label: 'امروز', value: summary.today, color: 'var(--accent)' },
            { label: 'پیش‌رو', value: summary.upcoming, color: 'var(--ink)' },
          ].map((s, i) => (
            <div key={i} style={{
              flex: 1, background: 'var(--surface)',
              border: '1px solid var(--border)', borderRadius: 14,
              padding: '10px 10px',
            }}>
              <div style={{ fontSize: 10.5, color: 'var(--muted)', marginBottom: 4 }}>{s.label}</div>
              <div style={{
                fontSize: 22, fontWeight: 700, color: s.color,
                fontVariantNumeric: 'tabular-nums', lineHeight: 1,
              }}>{window.faNumS(s.value)}</div>
            </div>
          ))}
        </div>

        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '4px 18px 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>

        <MonthGrid selected={selected} onSelect={setSelected} today={store.today} assignments={assignments} />

        <div style={{ height: 14 }} />

        <VisitList day={selected} visits={visits} />
      </div>
    </div>
  );
}

window.CalendarScreen = CalendarScreen;
