// field-visits.jsx — UI виїздів
//   window.VisitPanel      — рендериться у Drawer для задач kind === "visit"
//   window.NewVisitModal   — майстер створення виїзду (повний флоу)
//   window.VisitTypeBadge  — бейдж типу виїзду для списків / карток

(function () {
  const { useState } = React;
  const Ico = window.Ico;
  const money = (n) => (window.formatMoney ? window.formatMoney(n) : n);

  // ───────────────────────── helpers ─────────────────────────
  function KitIcon({ item, size }) {
    return <Ico name={item.icon || "dot"} size={size || 15} />;
  }

  function TransportPick({ mode, onPick }) {
    return (
      <div className="vt-trans-pick">
        {window.TRANSPORT_MODES.map(m => (
          <button key={m.id} type="button"
            className={`vt-trans-opt ${mode === m.id ? "is-on" : ""}`}
            onClick={() => onPick(m.id)} title={m.note}>
            <Ico name={m.icon} size={16} />
            <span>{m.label}</span>
          </button>
        ))}
      </div>
    );
  }

  // ═══════════════════════ VISIT TYPE BADGE ═══════════════════════
  function VisitTypeBadge({ typeId, small }) {
    const vt = window.getVisitType(typeId);
    return (
      <span className={`vt-badge ${small ? "is-small" : ""}`} title={`Виїзд · ${vt.label}`}>
        <Ico name="mapPin" size={small ? 11 : 12} />
        <span>{vt.short}</span>
      </span>
    );
  }
  window.VisitTypeBadge = VisitTypeBadge;

  // ═══════════════════════ READINESS STRIP ═══════════════════════
  function VisitPhaseStrip({ visit, readiness, onSetPhase }) {
    const phases = window.VISIT_PHASES;
    const curIdx = window.visitPhaseIndex(visit.phase);
    return (
      <div className="vt-phase">
        <div className="vt-phase-track">
          {phases.map((p, i) => (
            <React.Fragment key={p.id}>
              {i > 0 && <div className={`vt-phase-sep ${i <= curIdx ? "is-done" : ""}`}></div>}
              <button type="button"
                className={`vt-phase-node ${i < curIdx ? "is-done" : ""} ${i === curIdx ? "is-cur" : ""}`}
                onClick={() => onSetPhase(p.id)} title={p.label}>
                <span className="vt-phase-dot"><Ico name={i < curIdx ? "check" : p.icon} size={13} /></span>
                <span className="vt-phase-label">{p.label}</span>
              </button>
            </React.Fragment>
          ))}
        </div>
      </div>
    );
  }

  // ═══════════════════════ VISIT PANEL (у Drawer) ═══════════════════════
  function VisitPanel({ task, onTaskPatch }) {
    const visit = task.visit || {};
    const vt = window.getVisitType(visit.typeId);
    const obj = window.getObject(task.obj);
    const readiness = window.visitReadiness(visit);
    const team = window.DATA.TEAM || [];

    const patchVisit = (fn) => onTaskPatch(task.id, (x) => ({ ...x, visit: fn(x.visit || {}) }));
    const setTeam = (ids) => onTaskPatch(task.id, (x) => ({
      ...x, assignees: ids, assignee: ids[0] || null,
      visit: { ...(x.visit || {}), team: ids },
    }));
    const setPhase = (id) => {
      patchVisit(v => ({ ...v, phase: id }));
      // синхронізуємо статус задачі з фазою
      const map = { plan: "todo", ready: "live", done: "done" };
      onTaskPatch(task.id, (x) => ({ ...x, status: map[id] || x.status }));
    };

    // — team —
    const teamIds = visit.team || [];
    const addPerson = (id) => { if (id && !teamIds.includes(id)) setTeam([...teamIds, id]); };
    const removePerson = (id) => setTeam(teamIds.filter(x => x !== id));
    const notInTeam = team.filter(p => !teamIds.includes(p.id));

    // — kit —
    const kit = visit.kit || [];
    const patchKit = (fn) => patchVisit(v => ({ ...v, kit: fn(v.kit || []) }));
    const toggleProp = (id, prop) => patchKit(list => list.map(k => k.id === id ? { ...k, [prop]: !k[prop] } : k));
    const removeKit = (id) => patchKit(list => list.filter(k => k.id !== id));
    const addKit = (id) => {
      if (!id || kit.some(k => k.id === id)) return;
      patchKit(list => [...list, window.buildKitFromIds([id])[0]]);
    };
    const notInKit = window.VISIT_KIT_CATALOG.filter(c => !kit.some(k => k.id === c.id));
    const packedReq = kit.filter(k => !k.optional && k.packed).length;
    const totalReq = kit.filter(k => !k.optional).length;

    // — transport —
    const tr = visit.transport || { mode: "taxi", status: "todo" };
    const patchTr = (p) => patchVisit(v => ({ ...v, transport: { ...(v.transport || {}), ...p } }));
    const trMode = window.getTransportMode(tr.mode);

    // — coordination —
    const co = visit.coordination || { status: "draft" };
    const patchCo = (p) => patchVisit(v => ({ ...v, coordination: { ...(v.coordination || {}), ...p } }));
    const notify = () => patchCo({ notifiedAt: "щойно" });

    // — closeout —
    const cl = visit.closeout || { didItems: [], journalAN: false, photos: 0, drawings: false, expensesActual: null, files: [] };
    const patchCl = (p) => patchVisit(v => ({ ...v, closeout: { ...(v.closeout || {}), ...p } }));
    const [didInput, setDidInput] = useState("");
    const fillDid = () => patchCl({ didItems: vt.closeout.map((t, i) => ({ id: `did-${i}`, text: t, done: false })) });
    const addDid = () => {
      const t = didInput.trim(); if (!t) return;
      patchCl({ didItems: [...(cl.didItems || []), { id: "did-" + Math.random().toString(36).slice(2, 6), text: t, done: false }] });
      setDidInput("");
    };
    const toggleDid = (id) => patchCl({ didItems: (cl.didItems || []).map(d => d.id === id ? { ...d, done: !d.done } : d) });
    const removeDid = (id) => patchCl({ didItems: (cl.didItems || []).filter(d => d.id !== id) });
    const showCloseout = visit.phase !== "plan";

    return (
      <div className="vt-panel">
        {/* Тип + фаза + готовність */}
        <div className="pw-card vt-head-card">
          <div className="vt-head-top">
            <div className="vt-head-type">
              <span className="vt-head-ic" style={{ color: vt.color }}><Ico name={vt.icon} size={20} /></span>
              <div>
                <div className="vt-head-label">{vt.label}</div>
                <div className="vt-head-note">{vt.note}</div>
              </div>
            </div>
            <div className={`vt-ready-pill ${readiness.ready ? "is-ready" : ""}`}>
              {readiness.ready ? "Готовий до виїзду" : `Готовність ${readiness.pct}%`}
            </div>
          </div>

          <VisitPhaseStrip visit={visit} readiness={readiness} onSetPhase={setPhase} />

          <div className="vt-ready-grid">
            {readiness.steps.map(s => (
              <div key={s.key} className={`vt-ready-item ${s.done ? "is-done" : ""}`}>
                <span className="vt-ready-check"><Ico name={s.done ? "check" : "circle"} size={13} /></span>
                <span className="vt-ready-label">{s.label}</span>
                <span className="vt-ready-detail">{s.detail}</span>
              </div>
            ))}
          </div>

          {visit.phase === "plan" && (
            <button className="btn btn-primary btn-sm vt-phase-cta"
              disabled={!readiness.ready} style={!readiness.ready ? { opacity: 0.5, pointerEvents: "none" } : {}}
              onClick={() => setPhase("ready")}>
              <Ico name="checkCircle" size={15} /> Позначити готовим до виїзду
            </button>
          )}
          {visit.phase === "ready" && (
            <button className="btn btn-primary btn-sm vt-phase-cta" onClick={() => setPhase("done")}>
              <Ico name="check" size={15} /> Завершити виїзд
            </button>
          )}
          {visit.phase === "done" && (
            <div className="vt-done-note"><Ico name="checkCircle" size={15} /> Виїзд закрито. Заповніть результат нижче.</div>
          )}
        </div>

        {/* Погодження часу */}
        <div className="pw-card">
          <div className="pw-card-h"><Ico name="calendar" size={15} /> Погодження часу</div>
          <div className="vt-coord">
            <div className="vt-coord-when">
              <input className="cp-input" value={co.datetime || ""} placeholder="напр.: 28 трав, 10:00"
                onChange={(e) => patchCo({ datetime: e.target.value })} />
              <div className="vt-coord-seg">
                {Object.entries(window.COORD_STATUS).map(([k, v]) => (
                  <button key={k} type="button" className={`vt-seg-btn ${co.status === k ? "is-on tone-" + v.tone : ""}`}
                    onClick={() => patchCo({ status: k })}>{v.label}</button>
                ))}
              </div>
            </div>
            <div className="vt-contact">
              <div className="vt-contact-row">
                <input className="cp-input" value={co.contactName || ""} placeholder="Контактна особа"
                  onChange={(e) => patchCo({ contactName: e.target.value })} />
                <input className="cp-input" value={co.contactPhone || ""} placeholder="Телефон"
                  onChange={(e) => patchCo({ contactPhone: e.target.value })} />
              </div>
              <input className="cp-input" value={co.contactRole || ""} placeholder="Хто це / роль (замовник, виконроб…)"
                onChange={(e) => patchCo({ contactRole: e.target.value })} />
            </div>
            <div className="vt-notify">
              <button className="btn btn-sm" onClick={notify}><Ico name="megaphone" size={14} /> Нагадати учасникам</button>
              <span className="vt-notify-state">{co.notifiedAt ? `Сповіщено ${co.notifiedAt}` : "Ще не сповіщали"}</span>
            </div>
          </div>
        </div>

        {/* Хто їде */}
        <div className="pw-card">
          <div className="pw-card-h"><Ico name="users" size={15} /> Хто їде {teamIds.length > 0 && <span className="vt-count">{teamIds.length}</span>}</div>
          <div className="vt-team">
            {teamIds.length === 0 && <div className="vt-empty">Склад ще не визначено.</div>}
            {teamIds.map((id, i) => {
              const p = window.getTeam(id);
              if (!p) return null;
              return (
                <div key={id} className="vt-person">
                  <span className="team-avatar" style={{ width: 30, height: 30, fontSize: 11 }}>{p.initials}</span>
                  <div className="vt-person-meta">
                    <div className="vt-person-name">{p.name}{i === 0 ? <span className="vt-lead-tag">старший</span> : null}</div>
                    <div className="vt-person-role">{p.role}</div>
                  </div>
                  <button className="vt-x" onClick={() => removePerson(id)} title="Прибрати"><window.Icon.X /></button>
                </div>
              );
            })}
          </div>
          {notInTeam.length > 0 && (
            <div className="vt-add-row">
              <select className="cp-input" value="" onChange={(e) => addPerson(e.target.value)}>
                <option value="">+ Додати учасника…</option>
                {notInTeam.map(p => <option key={p.id} value={p.id}>{p.name} · {p.role}</option>)}
              </select>
            </div>
          )}
        </div>

        {/* Спорядження */}
        <div className="pw-card">
          <div className="pw-card-h">
            <Ico name="package" size={15} /> Спорядження
            <span className="vt-count">{packedReq}/{totalReq} зібрано</span>
          </div>
          <div className="vt-kit">
            {kit.map(k => {
              const asset = k.assetId ? window.getAsset(k.assetId) : null;
              return (
                <div key={k.id} className={`vt-kit-item ${k.packed ? "is-packed" : ""} ${k.future ? "is-future" : ""}`}>
                  <button className="vt-kit-check" onClick={() => toggleProp(k.id, "packed")} title={k.packed ? "Зняти" : "Позначити зібраним"}>
                    {k.packed && <window.Icon.Check />}
                  </button>
                  <span className="vt-kit-ic"><KitIcon item={k} /></span>
                  <div className="vt-kit-main">
                    <div className="vt-kit-name">{k.name}{k.future && <span className="vt-soon">скоро</span>}</div>
                    {k.kind === "instrument" && asset && (
                      <div className="vt-kit-asset">
                        <span className="td-mono">{asset.invNo}</span>
                        {k.checkedOut
                          ? <span className="status-tag tone-blue vt-mini-tag">видано зі складу</span>
                          : <span className="status-tag tone-neutral vt-mini-tag">на складі</span>}
                      </div>
                    )}
                    {k.kind === "instrument" && !asset && !k.future && (
                      <div className="vt-kit-asset"><span className="vt-kit-hint">обліковий прилад</span></div>
                    )}
                  </div>
                  {k.kind === "instrument" && !k.future && (
                    <button className={`vt-kit-co ${k.checkedOut ? "is-on" : ""}`} onClick={() => toggleProp(k.id, "checkedOut")}
                      title={k.checkedOut ? "Повернути на склад" : "Видати зі складу на виїзд"}>
                      {k.checkedOut ? "Повернути" : "Видати"}
                    </button>
                  )}
                  <button className="vt-x" onClick={() => removeKit(k.id)} title="Прибрати з комплекту"><window.Icon.X /></button>
                </div>
              );
            })}
          </div>
          {notInKit.length > 0 && (
            <div className="vt-add-row">
              <select className="cp-input" value="" onChange={(e) => addKit(e.target.value)}>
                <option value="">+ Додати до комплекту…</option>
                {notInKit.map(c => <option key={c.id} value={c.id}>{c.name}{c.kind === "instrument" ? " (прилад)" : ""}</option>)}
              </select>
            </div>
          )}
        </div>

        {/* Транспорт */}
        <div className="pw-card">
          <div className="pw-card-h"><Ico name="car" size={15} /> Транспорт</div>
          <TransportPick mode={tr.mode} onPick={(m) => patchTr({ mode: m })} />
          <div className="vt-trans-detail">
            <div className="vt-trans-field">
              <label className="vt-mini-label">{trMode.tickets ? "Квитки, ₴" : trMode.assetId ? "Пальне, ₴" : "Сума на касу, ₴"}</label>
              <input className="cp-input" type="number" value={tr.amount || ""} placeholder="0"
                onChange={(e) => patchTr({ amount: e.target.value ? Number(e.target.value) : null })} />
            </div>
            <div className="vt-trans-field">
              <label className="vt-mini-label">Статус</label>
              <div className="vt-coord-seg">
                {Object.entries(window.TRANSPORT_STATUS).map(([k, v]) => (
                  <button key={k} type="button" className={`vt-seg-btn ${tr.status === k ? "is-on tone-" + v.tone : ""}`}
                    onClick={() => patchTr({ status: k })}>{v.label}</button>
                ))}
              </div>
            </div>
          </div>
          <input className="cp-input vt-trans-note" value={tr.note || ""} placeholder="Деталі: маршрут, відстань, нотатка"
            onChange={(e) => patchTr({ note: e.target.value })} />
          {trMode.cashFromRegister && (tr.amount > 0) && (
            <div className="vt-cash-hint"><Ico name="banknote" size={14} /> {money(tr.amount)} ₴ — готівка з каси компанії</div>
          )}
        </div>

        {/* Результат виїзду */}
        {showCloseout && (
          <div className="pw-card vt-closeout">
            <div className="pw-card-h"><Ico name="clipboard" size={15} /> Результат виїзду</div>

            <div className="vt-did">
              <div className="vt-sub-h">Що зробили на місці
                {(!cl.didItems || cl.didItems.length === 0) &&
                  <button className="btn btn-sm vt-fill" onClick={fillDid}>Підставити типові</button>}
              </div>
              {(cl.didItems || []).map(d => (
                <div key={d.id} className={`vt-did-item ${d.done ? "is-done" : ""}`}>
                  <button className="vt-kit-check" onClick={() => toggleDid(d.id)}>{d.done && <window.Icon.Check />}</button>
                  <span className="vt-did-text">{d.text}</span>
                  <button className="vt-x" onClick={() => removeDid(d.id)}><window.Icon.X /></button>
                </div>
              ))}
              <div className="vt-add-row vt-did-add">
                <input className="cp-input" value={didInput} placeholder="Додати пункт…"
                  onChange={(e) => setDidInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") addDid(); }} />
                <button className="btn btn-sm" onClick={addDid} disabled={!didInput.trim()} style={!didInput.trim() ? { opacity: 0.5 } : {}}>Додати</button>
              </div>
            </div>

            <div className="vt-result-toggles">
              {visit.typeId === "supervision" && (
                <label className="vt-toggle">
                  <input type="checkbox" checked={!!cl.journalAN} onChange={(e) => patchCl({ journalAN: e.target.checked })} />
                  <Ico name="notebook" size={15} /> Запис у журнал авторського нагляду
                </label>
              )}
              <label className="vt-toggle">
                <input type="checkbox" checked={!!cl.drawings} onChange={(e) => patchCl({ drawings: e.target.checked })} />
                <Ico name="ruler" size={15} /> Обмірні креслення / ескізи готові
              </label>
              <div className="vt-photos">
                <Ico name="camera" size={15} /> Фотофіксація
                <button className="vt-step" onClick={() => patchCl({ photos: Math.max(0, (cl.photos || 0) - 5) })}>−</button>
                <span className="vt-photos-n">{cl.photos || 0} фото</span>
                <button className="vt-step" onClick={() => patchCl({ photos: (cl.photos || 0) + 5 })}>+</button>
              </div>
            </div>

            <div className="vt-expense">
              <div className="vt-expense-row">
                <span className="vt-mini-label">Витрати факт, ₴</span>
                <input className="cp-input vt-expense-in" type="number" value={cl.expensesActual ?? ""} placeholder={tr.amount || "0"}
                  onChange={(e) => patchCl({ expensesActual: e.target.value ? Number(e.target.value) : null })} />
                <span className="vt-expense-plan">план: {money(tr.amount || 0)} ₴</span>
              </div>
            </div>

            <div className="vt-files">
              <div className="vt-sub-h">Файли результату</div>
              {(vt.resultFiles || []).map((f, i) => (
                <div key={i} className="vt-file-ph"><Ico name="paperclip" size={14} /> {f}<button className="btn btn-ghost vt-file-up">Завантажити</button></div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }
  window.VisitPanel = VisitPanel;

  // ═══════════════════════ NEW VISIT MODAL ═══════════════════════
  function NewVisitModal({ onClose, onCreate, preset }) {
    const objects = window.DATA.OBJECTS || [];
    const team = window.DATA.TEAM || [];
    const days = window.WEEK_DAYS || [];
    const today = (days.find(d => d.isToday) || days[0] || {}).day || (window.TODAY ? window.TODAY.day : "");

    const [typeId, setTypeId] = useState((preset && preset.typeId) || "measure");
    const vt = window.getVisitType(typeId);
    const [objId, setObjId] = useState((preset && preset.objId) || "");
    const [title, setTitle] = useState("");
    const [teamIds, setTeamIds] = useState([]);
    const [day, setDay] = useState(today);
    const [time, setTime] = useState("");
    const [est, setEst] = useState("");
    const [datetime, setDatetime] = useState("");
    const [contactName, setContactName] = useState("");
    const [contactPhone, setContactPhone] = useState("");
    const [coordStatus, setCoordStatus] = useState("draft");
    const [trMode, setTrMode] = useState("taxi");
    const [trAmount, setTrAmount] = useState("");
    const [note, setNote] = useState("");
    const [kit, setKit] = useState(() => window.buildKitFromIds(window.getVisitType("measure").defaultKit));

    // зміна типу → перезбираємо комплект із дефолту цього типу
    const changeType = (id) => {
      setTypeId(id);
      setKit(window.buildKitFromIds(window.getVisitType(id).defaultKit));
    };

    React.useEffect(() => {
      const onKey = (e) => e.key === "Escape" && onClose();
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [onClose]);

    const toggleP = (id) => setTeamIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
    const removeKit = (id) => setKit(prev => prev.filter(k => k.id !== id));
    const addKit = (id) => { if (id && !kit.some(k => k.id === id)) setKit(prev => [...prev, window.buildKitFromIds([id])[0]]); };
    const notInKit = window.VISIT_KIT_CATALOG.filter(c => !kit.some(k => k.id === c.id));

    const canSubmit = title.trim().length > 0 && teamIds.length > 0;

    const submit = () => {
      if (!canSubmit) return;
      const selObj = objId ? objects.find(o => o.id === objId) : null;
      const task = {
        id: "v-" + Math.random().toString(36).slice(2, 8),
        kind: "visit", title: title.trim(),
        obj: objId || null, stage: selObj ? (selObj.activeStage || "project") : (objId ? "project" : "admin"),
        section: vt.section, assignee: teamIds[0], assignees: teamIds,
        day, time: time.trim() || null, est: est.trim() || null,
        status: "todo", note: note.trim() || null,
        subtasks: [], checklists: [],
        visit: {
          typeId, phase: "plan", team: teamIds, kit,
          transport: { mode: trMode, amount: trAmount ? Number(trAmount) : null, status: "todo", note: "" },
          coordination: { status: coordStatus, datetime: datetime.trim(), contactName: contactName.trim(), contactPhone: contactPhone.trim(), contactRole: "", notifiedAt: null },
          closeout: { didItems: [], journalAN: false, photos: 0, drawings: false, expensesActual: null, files: [] },
        },
      };
      onCreate && onCreate(window.normalizeTask ? window.normalizeTask(task) : task);
    };

    return (
      <>
        <div className="drawer-overlay" onClick={onClose}></div>
        <div className="report-modal nt-modal" style={{ maxWidth: 640, inset: "auto", top: 32, bottom: "auto", maxHeight: "calc(100vh - 64px)", left: "50%", transform: "translateX(-50%)", width: "calc(100% - 48px)" }}>
          <div className="report-toolbar">
            <button className="drawer-close" onClick={onClose}><window.Icon.X /></button>
            <div className="nt-head-icon"><Ico name="mapPin" /></div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Новий виїзд</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Спорядження · склад · транспорт · погодження</div>
            </div>
          </div>

          <div style={{ flex: 1, overflowY: "auto", padding: "22px 28px" }}>
            <div className="cp-grid">
              {/* Тип виїзду */}
              <div className="cp-row cp-row-full">
                <label className="cp-label">Тип виїзду</label>
                <div className="vt-type-grid">
                  {window.VISIT_TYPES.map(t => (
                    <button key={t.id} type="button" className={`vt-type-card ${typeId === t.id ? "is-active" : ""}`} onClick={() => changeType(t.id)}>
                      <span className="vt-type-ic" style={{ color: t.color }}><Ico name={t.icon} size={18} /></span>
                      <span className="vt-type-name">{t.short}</span>
                    </button>
                  ))}
                </div>
                <div className="nt-hint">{vt.note} Комплект підставлено за типом — можна відредагувати нижче.</div>
              </div>

              {/* Що / назва */}
              <div className="cp-row cp-row-full">
                <label className="cp-label">Назва виїзду <span className="cp-required">*</span></label>
                <input className="cp-input" value={title} autoFocus placeholder="Напр.: Обмір санвузлів, Зустріч із замовником на ділянці"
                  onChange={(e) => setTitle(e.target.value)} />
              </div>

              {/* Об'єкт */}
              <div className="cp-row">
                <label className="cp-label">Об'єкт</label>
                <select className="cp-input" value={objId} onChange={(e) => setObjId(e.target.value)}>
                  <option value="">— Без прив'язки —</option>
                  {objects.map(o => <option key={o.id} value={o.id}>{o.code} · {o.name}</option>)}
                </select>
              </div>

              {/* День */}
              <div className="cp-row">
                <label className="cp-label">День</label>
                <select className="cp-input" value={day} onChange={(e) => setDay(e.target.value)}>
                  {days.map(d => <option key={d.day} value={d.day}>{d.name}, {d.day} трав.{d.isToday ? " — сьогодні" : ""}</option>)}
                </select>
              </div>

              <div className="cp-row">
                <label className="cp-label">Час (необов'язково)</label>
                <input className="cp-input" value={time} placeholder="напр.: 10:00 — 13:00" onChange={(e) => setTime(e.target.value)} />
              </div>
              <div className="cp-row">
                <label className="cp-label">Тривалість</label>
                <input className="cp-input" value={est} placeholder="напр.: 3 год" onChange={(e) => setEst(e.target.value)} />
              </div>

              {/* Хто їде */}
              <div className="cp-row cp-row-full">
                <label className="cp-label">Хто їде {teamIds.length > 0 && <span className="nt-count">{teamIds.length}</span>} <span className="cp-required">*</span></label>
                <div className="nt-people">
                  {team.map(p => {
                    const on = teamIds.includes(p.id);
                    return (
                      <button key={p.id} type="button" className={`nt-person ${on ? "is-on" : ""}`} onClick={() => toggleP(p.id)}>
                        <span className="team-avatar nt-person-av">{p.initials}</span>
                        <span className="nt-person-name">{p.name}</span>
                        {p.role && <span className="nt-person-role">{p.role}</span>}
                        {on && <span className="nt-person-check"><Ico name="check" size={14} /></span>}
                      </button>
                    );
                  })}
                </div>
                <div className="nt-hint">Перший обраний — старший на виїзді.</div>
              </div>

              {/* Транспорт */}
              <div className="cp-row cp-row-full">
                <label className="cp-label">Транспорт</label>
                <TransportPick mode={trMode} onPick={setTrMode} />
                <div className="vt-trans-detail" style={{ marginTop: 10 }}>
                  <div className="vt-trans-field">
                    <label className="vt-mini-label">{window.getTransportMode(trMode).tickets ? "Квитки, ₴" : window.getTransportMode(trMode).assetId ? "Пальне, ₴" : "Сума на касу, ₴"}</label>
                    <input className="cp-input" type="number" value={trAmount} placeholder="0" onChange={(e) => setTrAmount(e.target.value)} />
                  </div>
                </div>
              </div>

              {/* Погодження */}
              <div className="cp-row cp-row-full">
                <label className="cp-label">Погодження часу</label>
                <div className="vt-contact-row">
                  <input className="cp-input" value={datetime} placeholder="Дата й час, напр.: 28 трав, 10:00" onChange={(e) => setDatetime(e.target.value)} />
                  <div className="vt-coord-seg">
                    {Object.entries(window.COORD_STATUS).map(([k, v]) => (
                      <button key={k} type="button" className={`vt-seg-btn ${coordStatus === k ? "is-on tone-" + v.tone : ""}`} onClick={() => setCoordStatus(k)}>{v.label}</button>
                    ))}
                  </div>
                </div>
                <div className="vt-contact-row" style={{ marginTop: 8 }}>
                  <input className="cp-input" value={contactName} placeholder="Контактна особа (замовник / виконроб)" onChange={(e) => setContactName(e.target.value)} />
                  <input className="cp-input" value={contactPhone} placeholder="Телефон" onChange={(e) => setContactPhone(e.target.value)} />
                </div>
              </div>

              {/* Комплект */}
              <div className="cp-row cp-row-full">
                <label className="cp-label">Комплект спорядження <span className="nt-count">{kit.length}</span></label>
                <div className="vt-kit vt-kit-compact">
                  {kit.map(k => (
                    <div key={k.id} className="vt-kit-item">
                      <span className="vt-kit-ic"><KitIcon item={k} /></span>
                      <div className="vt-kit-main"><div className="vt-kit-name">{k.name}{k.future && <span className="vt-soon">скоро</span>}</div></div>
                      {k.kind === "instrument" && !k.future && <span className="status-tag tone-blue vt-mini-tag">прилад</span>}
                      <button className="vt-x" onClick={() => removeKit(k.id)}><window.Icon.X /></button>
                    </div>
                  ))}
                </div>
                {notInKit.length > 0 && (
                  <div className="vt-add-row">
                    <select className="cp-input" value="" onChange={(e) => addKit(e.target.value)}>
                      <option value="">+ Додати до комплекту…</option>
                      {notInKit.map(c => <option key={c.id} value={c.id}>{c.name}{c.kind === "instrument" ? " (прилад)" : ""}</option>)}
                    </select>
                  </div>
                )}
              </div>

              <div className="cp-row cp-row-full">
                <label className="cp-label">Нотатка (необов'язково)</label>
                <textarea className="cp-input nt-textarea" rows={2} value={note} placeholder="Доступ на майданчик, контекст, що уточнити…" onChange={(e) => setNote(e.target.value)} />
              </div>
            </div>
          </div>

          <div className="nt-foot">
            <button className="btn" onClick={onClose}>Скасувати</button>
            <button className="btn btn-primary" disabled={!canSubmit} onClick={submit} style={!canSubmit ? { opacity: 0.5, pointerEvents: "none" } : {}}>
              Створити виїзд
            </button>
          </div>
        </div>
      </>
    );
  }
  window.NewVisitModal = NewVisitModal;

})();
