/* ctor-team.jsx — раздел «Команда»: объединяет Роли + Прорабов (штатных)
   и новый подраздел Субподрядчики с ценообразованием услуг/товаров.
   Адресует ревью Romа: «Роли» и «Прорабы» → в «Команда»; субподрядчики с
   себестоимостью (автоиндексация %/мес), маржой (%+₽), ценой клиенту и налогом;
   специализация (услуги / товары / оба) → связанные позиции. */
const { useState: tmhUseState } = React;
const tmhUid = window.ConstructorData.uid;

/* ---------- ценовой калькулятор (общий для услуг и товаров) ---------- */
function priceModel(cost, marginPct, taxPct) {
  const c = +cost || 0, m = +marginPct || 0, t = +taxPct || 0;
  const marginRub = Math.round(c * m / 100);
  const client = c + marginRub;
  const withTax = Math.round(client * (1 + t / 100));
  return { marginRub, client, withTax };
}
const tmhRub = (n) => (n || 0).toLocaleString('ru-RU');

/* ---------- сид субподрядчиков ---------- */
const SUBS_SEED = [
  { id: 'sub1', name: 'КлиматПро', kind: 'both', accredited: true, tax: 20,
    note: 'Кондиционеры + монтаж. Аккредитация пройдена.',
    services: [
      { id: 'sv1', label: 'Монтаж сплит-системы', cost: 8000, index: 5, margin: 35, kind: 'service' },
      { id: 'sv2', label: 'Кондиционер Royal Clima 9', cost: 32000, index: 3, margin: 22, kind: 'good' },
    ] },
  { id: 'sub2', name: 'ОкнаЛюкс', kind: 'both', accredited: true, tax: 20,
    note: 'Окна ПВХ под ключ — замер, демонтаж, монтаж, откосы.',
    services: [
      { id: 'sv3', label: 'Замена окна ПВХ (комплекс)', cost: 18000, index: 5, margin: 30, kind: 'service' },
      { id: 'sv4', label: 'Оконный профиль REHAU', cost: 12000, index: 4, margin: 18, kind: 'good' },
    ] },
  { id: 'sub3', name: 'ЧистоВывоз', kind: 'service', accredited: false, tax: 6,
    note: 'Вывоз строительного мусора. На аккредитации.',
    services: [
      { id: 'sv5', label: 'Вывоз мусора (контейнер 8 м³)', cost: 6500, index: 5, margin: 25, kind: 'service' },
    ] },
];
function loadSubs() { try { const r = localStorage.getItem('ctor_subs'); return r ? JSON.parse(r) : SUBS_SEED.map((s) => ({ ...s })); } catch (e) { return SUBS_SEED.map((s) => ({ ...s })); } }
function saveSubs(s) { try { localStorage.setItem('ctor_subs', JSON.stringify(s)); } catch (e) {} }

const SUB_KIND = { service: ['Услуга', '#1e40af', '#eff6ff'], good: ['Товар', '#166534', '#f0fdf4'] };
const SPEC = { service: 'Только услуги', good: 'Только товары', both: 'Услуги и товары' };

/* ---------- строка услуги/товара с ценовой моделью ---------- */
function ServiceRow({ sv, onPatch, onDel }) {
  const pm = priceModel(sv.cost, sv.margin, 0);
  const k = SUB_KIND[sv.kind];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 0.9fr 0.7fr 1fr 1fr 32px', gap: 10, alignItems: 'center', padding: '10px 12px', borderBottom: '1px solid var(--border-subtle)' }}>
      <div>
        <input value={sv.label} onChange={(e) => onPatch({ label: e.target.value })} style={tmhInput} />
        <span style={{ fontSize: 10.5, fontWeight: 700, color: k[1], background: k[2], padding: '1px 7px', borderRadius: 999, marginTop: 4, display: 'inline-block' }}>{k[0]}</span>
      </div>
      <div>
        <div style={tmhLbl}>Себестоимость</div>
        <input type="number" value={sv.cost} onChange={(e) => onPatch({ cost: +e.target.value })} style={tmhInput} />
        <div style={{ fontSize: 10, color: 'var(--text-tertiary)', marginTop: 2 }}>индекс {sv.index}%/мес</div>
      </div>
      <div>
        <div style={tmhLbl}>Маржа</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <input type="number" value={sv.margin} onChange={(e) => onPatch({ margin: +e.target.value })} style={{ ...tmhInput, width: 54 }} /><span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>%</span>
        </div>
        <div style={{ fontSize: 10.5, color: 'var(--success-strong)', marginTop: 2, fontWeight: 600 }}>(+{tmhRub(pm.marginRub)} ₽)</div>
      </div>
      <div>
        <div style={tmhLbl}>Цена клиенту</div>
        <div style={{ fontSize: 15, fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>{tmhRub(pm.client)} ₽</div>
      </div>
      <div>
        <div style={tmhLbl}>С налогом</div>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text-secondary)', fontVariantNumeric: 'tabular-nums' }}>{tmhRub(priceModel(sv.cost, sv.margin, sv._tax || 0).withTax)} ₽</div>
      </div>
      <button onClick={onDel} title="Удалить" style={tmhIconBtn}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" /></svg></button>
    </div>);
}

/* ---------- карточка субподрядчика ---------- */
function SubCard({ sub, onPatch, onDel }) {
  const [open, setOpen] = tmhUseState(false);
  const patchSv = (svId, patch) => onPatch({ services: sub.services.map((s) => s.id === svId ? { ...s, ...patch, _tax: sub.tax } : s) });
  const addSv = (kind) => onPatch({ services: [...sub.services, { id: tmhUid('sv'), label: kind === 'service' ? 'Новая услуга' : 'Новый товар', cost: 0, index: 5, margin: 25, kind }] });
  const total = sub.services.reduce((a, s) => a + priceModel(s.cost, s.margin, 0).client, 0);
  return (
    <div style={{ border: '1px solid var(--border-subtle)', borderRadius: 14, background: 'var(--card)', overflow: 'hidden', marginBottom: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', cursor: 'pointer' }} onClick={() => setOpen((o) => !o)}>
        <span style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--cat-plumb-bg)', color: 'var(--cat-plumb-fg)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 21h18M5 21V7l8-4v18M19 21V11l-6-4" /></svg>
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 15, fontWeight: 800, letterSpacing: '-.01em' }}>{sub.name}</span>
            {sub.accredited
              ? <span style={tmhBadge('var(--success-strong)', 'var(--success-soft)')}>аккредитован</span>
              : <span style={tmhBadge('var(--warning-strong)', 'var(--warning-soft)')}>на аккредитации</span>}
            <span style={tmhBadge('var(--text-secondary)', 'var(--secondary)')}>{SPEC[sub.kind]}</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 }}>{sub.services.length} позиций · от {tmhRub(total)} ₽ клиенту · налог {sub.tax}%</div>
        </div>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--text-tertiary)" strokeWidth="2" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}><polyline points="6 9 12 15 18 9" /></svg>
      </div>
      {open &&
        <div style={{ padding: '4px 16px 16px', borderTop: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end', padding: '12px 0' }}>
            <label style={{ fontSize: 12, color: 'var(--text-secondary)' }}>Специализация
              <select value={sub.kind} onChange={(e) => onPatch({ kind: e.target.value })} style={{ ...tmhInput, display: 'block', marginTop: 4 }}>
                <option value="service">Только услуги</option><option value="good">Только товары</option><option value="both">Услуги и товары</option>
              </select>
            </label>
            <label style={{ fontSize: 12, color: 'var(--text-secondary)' }}>Налог %
              <input type="number" value={sub.tax} onChange={(e) => onPatch({ tax: +e.target.value })} style={{ ...tmhInput, display: 'block', marginTop: 4, width: 80 }} />
            </label>
            <label style={{ fontSize: 12, color: 'var(--text-secondary)', display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer' }}>
              <input type="checkbox" checked={sub.accredited} onChange={(e) => onPatch({ accredited: e.target.checked })} />Аккредитация пройдена
            </label>
          </div>
          <input value={sub.note} onChange={(e) => onPatch({ note: e.target.value })} placeholder="Условия оказания услуг, сроки…" style={{ ...tmhInput, width: '100%', marginBottom: 10 }} />
          <div style={{ border: '1px solid var(--border-subtle)', borderRadius: 10, overflow: 'hidden' }}>
            {sub.services.map((sv) => <ServiceRow key={sv.id} sv={{ ...sv, _tax: sub.tax }} onPatch={(p) => patchSv(sv.id, p)} onDel={() => onPatch({ services: sub.services.filter((x) => x.id !== sv.id) })} />)}
            {sub.services.length === 0 && <div style={{ padding: 16, fontSize: 13, color: 'var(--text-tertiary)' }}>Нет позиций</div>}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
            <button onClick={() => addSv('service')} style={tmhGhost}>+ Услуга</button>
            <button onClick={() => addSv('good')} style={tmhGhost}>+ Товар</button>
            <div style={{ flex: 1 }} />
            <button onClick={onDel} style={{ ...tmhGhost, color: 'var(--destructive)', borderColor: 'color-mix(in srgb, var(--destructive) 30%, transparent)' }}>Удалить субподрядчика</button>
          </div>
        </div>}
    </div>);
}

/* ---------- подраздел Субподрядчики ---------- */
function SubcontractorsPanel({ subs, setSubs }) {
  const patch = (id, p) => setSubs((xs) => xs.map((s) => s.id === id ? { ...s, ...p } : s));
  const add = () => setSubs((xs) => [...xs, { id: tmhUid('sub'), name: 'Новый субподрядчик', kind: 'service', accredited: false, tax: 20, note: '', services: [] }]);
  const goods = subs.flatMap((s) => s.services.filter((v) => v.kind === 'good')).length;
  const svc = subs.flatMap((s) => s.services.filter((v) => v.kind === 'service')).length;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <p style={{ fontSize: 13.5, color: 'var(--text-secondary)', maxWidth: 640, margin: 0, lineHeight: 1.5 }}>
          Перечень услуг и товаров с ценообразованием. После добавления позиции становятся доступны в связанных полях: <b>товары</b> — в разделе материалов, <b>услуги</b> — в конструкторе смет. При добавлении товара система по умолчанию предлагает монтаж этой же компании.
        </p>
        <div style={{ flex: 1 }} />
        <button onClick={add} style={tmhPrimary}>+ Субподрядчик</button>
      </div>
      <div style={{ display: 'flex', gap: 22, padding: '0 2px 18px', flexWrap: 'wrap' }}>
        <span style={{ fontSize: 13, color: 'var(--text-tertiary)' }}><b style={{ fontSize: 20, fontWeight: 800, color: 'var(--foreground)' }}>{subs.length}</b> субподрядчиков</span>
        <span style={{ fontSize: 13, color: 'var(--text-tertiary)' }}><b style={{ fontSize: 20, fontWeight: 800, color: 'var(--foreground)' }}>{svc}</b> услуг → сметы</span>
        <span style={{ fontSize: 13, color: 'var(--text-tertiary)' }}><b style={{ fontSize: 20, fontWeight: 800, color: 'var(--foreground)' }}>{goods}</b> товаров → материалы</span>
      </div>
      {subs.map((s) => <SubCard key={s.id} sub={s} onPatch={(p) => patch(s.id, p)} onDel={() => setSubs((xs) => xs.filter((x) => x.id !== s.id))} />)}
    </div>);
}

/* ---------- хаб «Команда» ---------- */
function TeamHub({ roles, setRoles, foremen, setForemen, subs, setSubs, catalog, onStaffCount }) {
  const [sub, setSub] = tmhUseState('staff');
  const [grants, setGrants] = tmhUseState(() => (window.loadAccessGrants ? window.loadAccessGrants() : {}));
  React.useEffect(() => { if (window.saveAccessGrants) window.saveAccessGrants(grants); }, [grants]);
  // штат — новые коллекции профилей (ТЗ §4)
  const K = window.STAFF_KEYS || {};
  const [managers, setManagers] = tmhUseState(() => window.stLoad(K.managers, window.MANAGERS_SEED));
  const [designers, setDesigners] = tmhUseState(() => window.stLoad(K.designers, window.DESIGNERS_SEED));
  const [architects, setArchitects] = tmhUseState(() => window.stLoad(K.architects, window.ARCHITECTS_SEED));
  const [executors, setExecutors] = tmhUseState(() => window.stLoad(K.executors, window.EXECUTORS_SEED));
  React.useEffect(() => { window.stSave(K.managers, managers); }, [managers]);
  React.useEffect(() => { window.stSave(K.designers, designers); }, [designers]);
  React.useEffect(() => { window.stSave(K.architects, architects); }, [architects]);
  React.useEffect(() => { window.stSave(K.executors, executors); }, [executors]);
  React.useEffect(() => { if (onStaffCount) onStaffCount(managers.length + designers.length + architects.length + executors.length); }, [managers, designers, architects, executors]);
  const staffCount = managers.length + designers.length + architects.length + foremen.length + executors.length;
  const SUBTABS = [
    { id: 'staff', l: 'Команда (штат)', n: staffCount },
    { id: 'subs', l: 'Субподрядчики', n: subs.length },
    { id: 'access', l: 'Доступ', n: window.countDelegates ? window.countDelegates(grants) : 0 },
  ];
  return (
    <div>
      <div style={{ ...ctorStyles.segmentedTrack, marginBottom: 20 }}>
        {SUBTABS.map((t) => {
          const on = sub === t.id;
          return (
            <button key={t.id} type="button" onClick={() => setSub(t.id)} style={ctorStyles.segmentedBtn(on)}>
              {t.l}
              <span style={ctorStyles.segmentedCount(on)}>{t.n}</span>
            </button>
          );
        })}
      </div>
      <div className="ctor-fade" key={sub}>
        {sub === 'staff' && <StaffPanel managers={managers} setManagers={setManagers} designers={designers} setDesigners={setDesigners} architects={architects} setArchitects={setArchitects} executors={executors} setExecutors={setExecutors} foremen={foremen} setForemen={setForemen} roles={roles} setRoles={setRoles} catalog={catalog} />}
        {sub === 'subs' && <SubcontractorsPanel subs={subs} setSubs={setSubs} />}
        {sub === 'access' && <AccessPanel grants={grants} setGrants={setGrants} />}
      </div>
    </div>);
}

/* ---------- styles ---------- */
const tmhInput = { fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: 'var(--foreground)', background: 'var(--input-background)', border: '1px solid var(--c-border)', borderRadius: 8, padding: '7px 10px', outline: 'none', width: '100%' };
const tmhLbl = { fontSize: 10, fontWeight: 700, color: 'var(--text-tertiary)', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 3 };
const tmhGhost = { fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, color: 'var(--text-secondary)', background: 'var(--glass-bg-strong)', border: '1px solid var(--c-border)', borderRadius: 999, padding: '7px 14px', cursor: 'pointer' };
const tmhPrimary = { fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: '#fff', background: 'var(--ink)', border: 'none', borderRadius: 999, padding: '9px 16px', cursor: 'pointer' };
const tmhIconBtn = { width: 30, height: 30, borderRadius: 8, border: '1px solid var(--c-border)', background: 'var(--glass-bg-strong)', color: 'var(--text-tertiary)', cursor: 'pointer', display: 'grid', placeItems: 'center' };
function tmhBadge(c, bg) { return { fontSize: 10.5, fontWeight: 700, color: c, background: bg, padding: '2px 8px', borderRadius: 999 }; }

Object.assign(window, { TeamHub, SubcontractorsPanel, loadSubs, saveSubs });
