// MessagesScreen — inbox / sent / compose, Persian RTL.
//
// Permission model (enforced again on the server):
//   • promoter                       → may message their superiors only, one at a time.
//   • supervisor/manager             → may message their subtree + superiors, group sends allowed.
//   • senior_manager/admin           → may message anyone, including group sends.
//
// Used two ways:
//   <window.MessagesScreen onBack={fn} />   — full screen with a back button (dashboard)
//   <window.MessagesScreen embedded />       — chrome-less, inside an admin tab

const { useState: useStateMsg, useEffect: useEffectMsg, useMemo: useMemoMsg } = React;

const MSG_ROLE_LABEL = {
  promoter: 'پروموتور', supervisor: 'سرپرست', manager: 'مدیر',
  senior_manager: 'مدیر ارشد', admin: 'ادمین',
  user: 'پروموتور', // legacy alias
};

// ISO-UTC string → "۲ خرداد" style is overkill here; show a compact local time/date.
function fmtMsgTime(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  if (isNaN(d)) return '';
  const fa = (n) => window.faNumS(String(n).padStart(2, '0'));
  const sameDay = (a, b) =>
    a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  const now = new Date();
  const hm = `${fa(d.getHours())}:${fa(d.getMinutes())}`;
  if (sameDay(d, now)) return hm;
  return `${window.faNumS(d.getDate())}/${window.faNumS(d.getMonth() + 1)} · ${hm}`;
}

function RoleBadge({ role }) {
  const label = MSG_ROLE_LABEL[role] || role;
  const isStaff = role && role !== 'promoter' && role !== 'user';
  return (
    <span style={{
      fontSize: 9.5, fontWeight: 700, padding: '2px 7px', borderRadius: 99,
      background: isStaff
        ? 'color-mix(in oklab, var(--accent) 14%, transparent)'
        : 'var(--icon-bg)',
      color: isStaff ? 'var(--accent)' : 'var(--muted)',
      whiteSpace: 'nowrap',
    }}>{label}</span>
  );
}

function Avatar({ name, initials, tone = 'neutral' }) {
  const init = initials || (name || '?').trim().slice(0, 1);
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 99, flexShrink: 0,
      background: tone === 'accent' ? 'var(--accent)' : 'var(--icon-bg)',
      color: tone === 'accent' ? '#fff' : 'var(--ink)',
      border: tone === 'accent' ? 'none' : '1px solid var(--border)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 12, fontWeight: 700,
    }}>{init}</div>
  );
}

// ---------- one message row in a list ----------
function MessageRow({ msg, side, expanded, onToggle }) {
  // side: 'inbox' (show sender) | 'sent' (show recipient)
  const who = side === 'inbox'
    ? { name: msg.fromName, role: msg.fromRole }
    : { name: msg.groupId ? 'گروهی' : msg.toName, role: null };
  const unread = side === 'inbox' && !msg.read;

  return (
    <button
      onClick={onToggle}
      style={{
        all: 'unset', cursor: 'pointer', display: 'block', width: '100%',
        boxSizing: 'border-box', textAlign: 'right',
        padding: '12px 14px',
        borderTop: '1px solid var(--border)',
        background: unread ? 'color-mix(in oklab, var(--accent) 5%, transparent)' : 'transparent',
      }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
        <Avatar name={who.name} tone={unread ? 'accent' : 'neutral'} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 2 }}>
            <span style={{
              fontSize: 13.5, fontWeight: unread ? 800 : 600, color: 'var(--ink)',
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{who.name || '—'}</span>
            {who.role && <RoleBadge role={who.role} />}
            {side === 'sent' && msg.groupId && (
              <span style={{ fontSize: 9.5, color: 'var(--muted)' }}>چند گیرنده</span>
            )}
            <span style={{
              marginInlineStart: 'auto', flexShrink: 0,
              fontSize: 10.5, color: 'var(--muted)',
              fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            }}>{fmtMsgTime(msg.at)}</span>
          </div>
          {side === 'inbox' && msg.fromStoreName && (
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              fontSize: 10.5, fontWeight: 600, color: 'var(--accent)',
              background: 'color-mix(in oklab, var(--accent) 10%, transparent)',
              padding: '2px 8px', borderRadius: 99, marginBottom: 4,
            }}>
              <window.IconPin size={11} color="currentColor" />
              {msg.fromStoreName}
            </div>
          )}
          {msg.subject && (
            <div style={{
              fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 2,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{msg.subject}</div>
          )}
          <div style={{
            fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5,
            ...(expanded ? {} : {
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }),
          }}>{msg.body}</div>
        </div>
        {unread && (
          <span style={{
            width: 8, height: 8, borderRadius: 99, background: 'var(--accent)',
            flexShrink: 0, marginTop: 6,
          }} />
        )}
      </div>
    </button>
  );
}

// ---------- list of messages (inbox or sent) ----------
function MessageList({ items, side, emptyText, onOpen }) {
  const [openId, setOpenId] = useStateMsg(null);
  if (!items.length) {
    return (
      <div style={{
        padding: '48px 24px', textAlign: 'center',
        color: 'var(--muted)', fontSize: 13,
      }}>{emptyText}</div>
    );
  }
  return (
    <div>
      {items.map(m => (
        <MessageRow
          key={m.id}
          msg={m}
          side={side}
          expanded={openId === m.id}
          onToggle={() => {
            const next = openId === m.id ? null : m.id;
            setOpenId(next);
            if (next && side === 'inbox' && !m.read) onOpen?.(m);
          }}
        />
      ))}
    </div>
  );
}

// ---------- compose ----------
function Compose({ recipients, canGroup, onCancel, onSent }) {
  const [selected, setSelected] = useStateMsg([]); // userIds
  const [sendAll, setSendAll] = useStateMsg(false);
  const [subject, setSubject] = useStateMsg('');
  const [body, setBody] = useStateMsg('');
  const [sending, setSending] = useStateMsg(false);
  const [error, setError] = useStateMsg('');

  const toggle = (id) => {
    setSendAll(false);
    if (canGroup) {
      setSelected(sel => sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]);
    } else {
      setSelected([id]); // single recipient for field users
    }
  };

  const recipientCount = sendAll ? recipients.length : selected.length;
  const canSend = body.trim().length > 0 && recipientCount > 0 && !sending;

  const submit = async () => {
    if (!canSend) return;
    setSending(true);
    setError('');
    const payload = sendAll
      ? { all: true, subject, body }
      : { toUserIds: selected, subject, body };
    const r = await window.appActions.sendMessage(payload);
    setSending(false);
    if (r.ok) onSent?.();
    else setError(r.error || 'خطا در ارسال پیام');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 16px 16px' }}>
        {/* recipients */}
        <div style={{
          fontSize: 11, color: 'var(--muted)', fontWeight: 600,
          letterSpacing: '0.04em', margin: '6px 2px 8px',
        }}>
          گیرنده {canGroup ? '(می‌توانید چند نفر یا همه را انتخاب کنید)' : ''}
        </div>

        {canGroup && (
          <button
            onClick={() => { setSendAll(a => !a); setSelected([]); }}
            style={{
              all: 'unset', cursor: 'pointer', boxSizing: 'border-box',
              display: 'flex', alignItems: 'center', gap: 10, width: '100%',
              padding: '11px 12px', borderRadius: 12, marginBottom: 8,
              background: sendAll ? 'var(--accent)' : 'var(--surface)',
              color: sendAll ? '#fff' : 'var(--ink)',
              border: sendAll ? '1px solid var(--accent)' : '1px solid var(--border)',
            }}>
            <span style={{
              width: 22, height: 22, borderRadius: 7, flexShrink: 0,
              border: sendAll ? '1px solid rgba(255,255,255,0.6)' : '1px solid var(--border)',
              background: sendAll ? 'rgba(255,255,255,0.18)' : 'var(--icon-bg)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 13, fontWeight: 800,
            }}>{sendAll ? '✓' : ''}</span>
            <span style={{ fontSize: 13.5, fontWeight: 700 }}>ارسال به همه</span>
            <span style={{
              marginInlineStart: 'auto', fontSize: 11,
              color: sendAll ? 'rgba(255,255,255,0.85)' : 'var(--muted)',
            }}>{window.faNumS(recipients.length)} نفر</span>
          </button>
        )}

        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 14, overflow: 'hidden', opacity: sendAll ? 0.5 : 1,
          pointerEvents: sendAll ? 'none' : 'auto',
        }}>
          {recipients.length === 0 && (
            <div style={{ padding: '18px', textAlign: 'center', fontSize: 12.5, color: 'var(--muted)' }}>
              گیرنده‌ای در دسترس نیست
            </div>
          )}
          {recipients.map((r, i) => {
            const active = selected.includes(r.id);
            return (
              <button key={r.id}
                onClick={() => toggle(r.id)}
                style={{
                  all: 'unset', cursor: 'pointer', boxSizing: 'border-box',
                  display: 'flex', alignItems: 'center', gap: 11, width: '100%',
                  padding: '10px 12px',
                  borderTop: i ? '1px solid var(--border)' : 'none',
                  background: active ? 'color-mix(in oklab, var(--accent) 9%, transparent)' : 'transparent',
                }}>
                <Avatar name={r.name} initials={r.initials} tone={active ? 'accent' : 'neutral'} />
                <span style={{ fontSize: 13.5, fontWeight: active ? 700 : 600, color: 'var(--ink)' }}>{r.name}</span>
                <RoleBadge role={r.role} />
                <span style={{
                  marginInlineStart: 'auto', width: 20, height: 20, borderRadius: canGroup ? 6 : 99,
                  border: active ? '1px solid var(--accent)' : '1px solid var(--border)',
                  background: active ? 'var(--accent)' : 'transparent',
                  color: '#fff', flexShrink: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 12, fontWeight: 800,
                }}>{active ? '✓' : ''}</span>
              </button>
            );
          })}
        </div>

        {/* subject */}
        <div style={{
          fontSize: 11, color: 'var(--muted)', fontWeight: 600,
          letterSpacing: '0.04em', margin: '16px 2px 8px',
        }}>موضوع (اختیاری)</div>
        <input
          value={subject}
          onChange={e => setSubject(e.target.value)}
          placeholder="موضوع پیام"
          style={{
            all: 'unset', boxSizing: 'border-box', width: '100%',
            padding: '11px 13px', borderRadius: 12,
            background: 'var(--surface)', border: '1px solid var(--border)',
            fontSize: 13.5, color: 'var(--ink)',
            fontFamily: 'Vazirmatn, system-ui, sans-serif',
          }} />

        {/* body */}
        <div style={{
          fontSize: 11, color: 'var(--muted)', fontWeight: 600,
          letterSpacing: '0.04em', margin: '16px 2px 8px',
        }}>متن پیام</div>
        <textarea
          value={body}
          onChange={e => setBody(e.target.value)}
          placeholder="پیام خود را بنویسید…"
          rows={5}
          style={{
            all: 'unset', boxSizing: 'border-box', width: '100%',
            padding: '12px 13px', borderRadius: 12, minHeight: 110,
            background: 'var(--surface)', border: '1px solid var(--border)',
            fontSize: 13.5, color: 'var(--ink)', lineHeight: 1.6,
            fontFamily: 'Vazirmatn, system-ui, sans-serif', resize: 'none',
          }} />

        {error && (
          <div style={{ marginTop: 12, fontSize: 12.5, color: 'var(--danger)', fontWeight: 600 }}>{error}</div>
        )}
      </div>

      {/* action bar */}
      <div style={{
        flexShrink: 0, padding: '10px 16px 16px',
        display: 'flex', gap: 10, borderTop: '1px solid var(--border)',
        background: 'var(--bg)',
      }}>
        <button onClick={onCancel} style={{
          all: 'unset', cursor: 'pointer', padding: '12px 18px', borderRadius: 12,
          background: 'var(--surface)', border: '1px solid var(--border)',
          fontSize: 13.5, fontWeight: 600, color: 'var(--ink)',
        }}>انصراف</button>
        <button
          onClick={submit}
          disabled={!canSend}
          style={{
            all: 'unset', cursor: canSend ? 'pointer' : 'default', flex: 1,
            padding: '12px 18px', borderRadius: 12, textAlign: 'center',
            background: canSend ? 'var(--accent)' : 'var(--icon-bg)',
            color: canSend ? '#fff' : 'var(--muted)',
            fontSize: 13.5, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
          <window.IconSend size={17} color={canSend ? '#fff' : 'var(--muted)'} />
          {sending ? 'در حال ارسال…'
            : recipientCount > 1 ? `ارسال به ${window.faNumS(recipientCount)} نفر` : 'ارسال پیام'}
        </button>
      </div>
    </div>
  );
}

// ---------- main screen ----------
function MessagesScreen({ onBack, embedded = false }) {
  const app = window.useAppStore();
  const [tab, setTab] = useStateMsg('inbox'); // 'inbox' | 'sent'
  const [composing, setComposing] = useStateMsg(false);
  const [recipients, setRecipients] = useStateMsg([]);
  const [canGroup, setCanGroup] = useStateMsg(false);

  // Fresh inbox/sent + recipients on mount.
  useEffectMsg(() => {
    window.appActions.reloadMessages();
    window.appActions.fetchRecipients().then(r => {
      setRecipients(r.recipients);
      setCanGroup(r.canGroup);
    });
  }, []);

  const unread = useMemoMsg(
    () => app.inbox.filter(m => !m.read).length,
    [app.inbox]
  );

  const body = (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      {/* segmented control */}
      <div style={{ display: 'flex', gap: 6, padding: '6px 16px 10px', flexShrink: 0 }}>
        {[
          { id: 'inbox', label: 'دریافتی', badge: unread },
          { id: 'sent',  label: 'ارسالی' },
        ].map(s => {
          const active = tab === s.id;
          return (
            <button key={s.id}
              onClick={() => setTab(s.id)}
              style={{
                all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center',
                padding: '9px 4px', borderRadius: 10, position: 'relative',
                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,
              }}>
              {s.label}
              {s.badge > 0 && (
                <span style={{
                  position: 'absolute', top: 5, insetInlineEnd: 8,
                  minWidth: 16, height: 16, borderRadius: 99,
                  background: 'var(--danger)', color: '#fff',
                  fontSize: 9, fontWeight: 700, padding: '0 4px',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{window.faNumS(s.badge)}</span>
              )}
            </button>
          );
        })}
      </div>

      <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
        {tab === 'inbox' ? (
          <MessageList
            items={app.inbox}
            side="inbox"
            emptyText="پیامی دریافت نکرده‌اید"
            onOpen={(m) => window.appActions.markMessageRead(m.id)}
          />
        ) : (
          <MessageList
            items={app.sentMessages}
            side="sent"
            emptyText="پیامی ارسال نکرده‌اید"
          />
        )}
      </div>

      {/* new-message FAB */}
      <button
        onClick={() => setComposing(true)}
        style={{
          position: 'absolute', insetInlineStart: 18, bottom: 18,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '12px 18px', borderRadius: 99, cursor: 'pointer',
          border: 'none', background: 'var(--accent)', color: '#fff',
          fontSize: 13.5, fontWeight: 700,
          fontFamily: 'Vazirmatn, system-ui, sans-serif',
          boxShadow: '0 8px 22px -6px color-mix(in oklab, var(--accent) 70%, transparent)',
        }}>
        <window.IconSend size={17} color="#fff" />
        پیام جدید
      </button>
    </div>
  );

  const compose = (
    <Compose
      recipients={recipients}
      canGroup={canGroup}
      onCancel={() => setComposing(false)}
      onSent={() => { setComposing(false); setTab('sent'); }}
    />
  );

  // Embedded (admin tab): no outer frame / back header.
  if (embedded) {
    return (
      <div style={{ height: '100%', position: 'relative', display: 'flex', flexDirection: 'column' }}>
        {composing ? compose : body}
      </div>
    );
  }

  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', position: 'relative',
    }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 8px', flexShrink: 0,
      }}>
        <button onClick={composing ? () => setComposing(false) : 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 }}>{composing ? 'پیام جدید' : 'پیام‌ها'}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>
            {composing ? 'نوشتن و ارسال پیام' : 'دریافت و ارسال پیام'}
          </div>
        </div>
        <div style={{ width: 38 }} />
      </div>

      {composing ? compose : body}
    </div>
  );
}

window.MessagesScreen = MessagesScreen;
