/* deal-team.jsx — карточка «Команда сделки»: менеджер · замерщик · дизайнер · прораб · исполнители. Кто назначен и откуда
   (этап «Замер», проект), назначение из списка аккаунтов/команды Конструктора или своё имя. Данные — window.DealTeam.
   Exports on window: DealTeamCard */
(function () {
  const { Badge, Button } = window.DesignSystem_9e0a09;
  const { Ic } = window;
  const { useState, useEffect, useMemo } = React;
  const initials = (n) => String(n || '').split(/\s+/).map((w) => w[0]).filter(Boolean).slice(0, 2).join('').toUpperCase() || '·';

  function Assign({ role, onPick, onClose }) {
    const T = window.DealTeam; const opts = T ? T.options(role) : [];
    const [own, setOwn] = useState('');
    return (
      <div className="dt-assign">
        {opts.length > 0 && <div className="dt-assign-l">{opts.map((o) => <button key={o.id || o.name} type="button" className="fe-chip" onClick={() => onPick(o)}>{o.name}{o.sub ? <span className="dt-muted"> · {o.sub}</span> : null}</button>)}</div>}
        <div className="dt-assign-own">
          <input className="cc-ir-input" value={own} placeholder="Или имя вручную" onChange={(e) => setOwn(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && own.trim()) onPick({ id: null, name: own.trim() }); }} />
          <Button variant="secondary" size="sm" disabled={!own.trim()} onClick={() => onPick({ id: null, name: own.trim() })}>Назначить</Button>
          <Button variant="ghost" size="sm" onClick={onClose}>Отмена</Button>
        </div>
      </div>
    );
  }

  /* карточка человека: фото (или инициалы), имя, специализация; при необходимости — действие */
  const ROLE_TONE = { manager: 'var(--chart-3)', measurer: 'var(--info)', designer: 'var(--primary)', foreman: 'var(--success-strong)', executors: 'var(--chart-2)' };
  function PersonCard({ p, role, roleLabel, note, action, onClick }) {
    const tone = ROLE_TONE[role] || 'var(--primary)';
    const spec = p.trade || roleLabel || p.roleLabel || '';
    const Tag = onClick ? 'button' : 'div';
    return (
      <Tag type={onClick ? 'button' : undefined} className={'pc' + (p.gone ? ' is-gone' : '') + (onClick ? ' is-click' : '')} onClick={onClick} title={p.phone || undefined}>
        {p.photo ? <img className="pc-ava" src={p.photo} alt="" /> : <span className="pc-ava" style={{ background: tone }}>{initials(p.name)}</span>}
        <span className="pc-b">
          <b className="pc-n">{p.name}</b>
          <span className="pc-r">{spec}</span>
          {note !== false && (p.gone ? <span className="pc-m pc-m--gone">уволен — передать</span> : note ? <span className="pc-m">{note}</span> : null)}
        </span>
        {action}
      </Tag>
    );
  }
  function EmptyCard({ role, label, hint, action }) {
    return (
      <div className="pc is-empty">
        <span className="pc-ava pc-ava--empty"><Ic n={(window.DealTeam.ROLES.find((r) => r.id === role) || {}).icon || 'user-round'} s={15} /></span>
        <span className="pc-b"><b className="pc-n">{label}</b><span className="pc-r">{hint || 'не назначен'}</span></span>
        {action}
      </div>
    );
  }
  window.PersonCard = PersonCard;

  function DealTeamCard({ dealId, canEdit, compact, title }) {
    const T = window.DealTeam;
    const [tick, setTick] = useState(0);
    const [edit, setEdit] = useState(null);
    useEffect(() => { const up = () => setTick((x) => x + 1); ['remontpro:intake-updated', 'storage', 'obitel:sync'].forEach((e) => window.addEventListener(e, up)); const P = window.ProjectStore; const un = P && P.subscribe ? P.subscribe(up) : null; return () => { ['remontpro:intake-updated', 'storage', 'obitel:sync'].forEach((e) => window.removeEventListener(e, up)); if (un) un(); }; }, []);
    const data = useMemo(() => (T && dealId ? T.get(dealId) : null), [T, dealId, tick]);
    if (!T || !data) return null;
    const { roles, project } = data;
    const filled = T.ROLES.filter((r) => (r.many ? roles[r.id].length : roles[r.id] && !roles[r.id].tentative)).length;
    const single = T.ROLES.filter((r) => !r.many);
    const crew = roles.executors || [];
    return (
      <div className={'dt' + (compact ? ' dt--compact' : '')}>
        {title !== false && <div className="dt-h"><b>{title || 'Команда сделки'}</b><span className="dt-muted">{filled} из {T.ROLES.length}{project ? ' · проект ' + project.id : ''}</span></div>}
        <div className="pc-grid">
          {single.map((r) => {
            const v = roles[r.id];
            if (v && !v.tentative) {
              return (
                <React.Fragment key={r.id}>
                  <PersonCard p={v} role={r.id} roleLabel={r.label} note={v.src}
                    action={canEdit && edit !== r.id && !(r.id === 'foreman' && project) ? <button type="button" className="pc-act" title="Сменить" onClick={() => setEdit(r.id)}><Ic n="pencil" s={12} /></button> : null} />
                  {edit === r.id && <div className="pc-assign"><Assign role={r.id} onPick={(p) => { T.assign(dealId, r.id, p); setEdit(null); }} onClose={() => setEdit(null)} /></div>}
                </React.Fragment>);
            }
            if (v && v.tentative) {
              return <EmptyCard key={r.id} role={r.id} label={r.label} hint={'не назначен · вы — ' + v.name}
                action={<button type="button" className="pc-act pc-act--cta" onClick={() => T.assign(dealId, 'manager', { id: v.id, name: v.name, how: 'взял в работу' })}>Взять</button>} />;
            }
            if (r.id === 'foreman' && !project) return <EmptyCard key={r.id} role={r.id} label={r.label} hint="после запуска проекта" />;
            return (
              <React.Fragment key={r.id}>
                <EmptyCard role={r.id} label={r.label} hint={r.id === 'manager' ? 'подтянется по личной ссылке' : 'не назначен'}
                  action={canEdit && edit !== r.id ? <button type="button" className="pc-act" onClick={() => setEdit(r.id)}>Назначить</button> : null} />
                {edit === r.id && <div className="pc-assign"><Assign role={r.id} onPick={(p) => { T.assign(dealId, r.id, p); setEdit(null); }} onClose={() => setEdit(null)} /></div>}
              </React.Fragment>);
          })}
          {crew.map((p, i) => <PersonCard key={p.id || i} p={p} role="executors" roleLabel="Исполнитель" note={p.src} />)}
          {!crew.length && <EmptyCard role="executors" label="Исполнители" hint={project ? 'бригада не назначена' : 'после запуска проекта'} />}
        </div>
      </div>
    );
  }
  window.DealTeamCard = DealTeamCard;
  /* только назначенные люди, без пустых ролей и действий — для клиента и шапок */
  function TeamStrip({ dealId, title }) {
    const T = window.DealTeam;
    const [tick, setTick] = useState(0);
    useEffect(() => { const up = () => setTick((x) => x + 1); ['remontpro:intake-updated', 'storage', 'obitel:sync'].forEach((e) => window.addEventListener(e, up)); return () => ['remontpro:intake-updated', 'storage', 'obitel:sync'].forEach((e) => window.removeEventListener(e, up)); }, []);
    const data = useMemo(() => (T && dealId ? T.get(dealId) : null), [T, dealId, tick]);
    if (!T || !data) return null;
    const { roles } = data;
    const list = [];
    T.ROLES.forEach((r) => { const v = roles[r.id];
      if (r.many) (v || []).forEach((p) => list.push({ p, role: r.id, label: r.label }));
      else if (v && !v.tentative && !v.gone) list.push({ p: v, role: r.id, label: r.label }); });
    if (!list.length) return null;
    return (
      <div className="pc-strip">
        {title !== false && <div className="pc-strip-h">{title || 'Ваша команда'}</div>}
        <div className="pc-grid pc-grid--tight">
          {list.map((x, i) => <PersonCard key={(x.p.id || '') + i} p={x.p} role={x.role} roleLabel={x.label} note={false} />)}
        </div>
      </div>
    );
  }
  window.TeamStrip = TeamStrip;
})();
