// screens-entry.jsx — New Work Log flow (3 layouts), ATA selector (3 variants),
// C/B reset sheet, photo capture. Exported to window.
const { useState: useS, useMemo } = React;

/* ---------------------------- field sub-parts ---------------------------- */
function AircraftPick({ data, set }) {
  const flt = data.flight ? FLIGHTS.find((f) => f.id === data.flight) : FLIGHTS.find((f) => f.reg === data.reg);
  return (
    <div className="acpick">
      <div className="chiprow wrap">
        {FLEET.map((a) => <Chip key={a.reg} mono on={data.reg === a.reg} onClick={() => { set("reg", a.reg); const cf = FLIGHTS.find((f) => f.reg === a.reg); set("flight", cf ? cf.id : null); }}>{a.reg}</Chip>)}
      </div>
      {flt && (
        <div className="acpick-flt">
          <Ic.flight width="15" height="15" />
          <span className="mono">{flt.id}</span><span>{flt.from}→{flt.to}</span>
          <span className="acpick-fuel mono"><Ic.fuel width="13" height="13" /> {flt.fuelUplift.toLocaleString()}{flt.fuelUnit}</span>
          <span className="acpick-auto">From API</span>
        </div>
      )}
    </div>
  );
}

function AtaPick({ data, onOpen }) {
  const a = ATA.find((x) => x.c === data.ata);
  return (
    <button className={"atapick" + (a ? " atapick--set" : "")} onClick={onOpen}>
      {a ? <><AtaBadge code={a.c} /><span className="atapick-name">{a.t} · {a.th}</span></> : <span className="atapick-ph">Select ATA chapter</span>}
      <Ic.chevron width="18" height="18" />
    </button>
  );
}

function PartsEditor({ data, set }) {
  const [pn, setPn] = useS(""); const [off, setOff] = useS(""); const [on, setOn] = useS("");
  const add = () => { if (!pn) return; set("parts", [...data.parts, { pn, off: off || "—", on: on || "—" }]); setPn(""); setOff(""); setOn(""); };
  return (
    <div className="parts-ed">
      {data.parts.map((p, i) => (
        <div key={i} className="partrow partrow--ed">
          <Ic.part width="16" height="16" />
          <div><div className="mono partpn">{p.pn}</div><div className="partoff mono">OFF {p.off} → ON {p.on}</div></div>
          <button className="iconbtn" onClick={() => set("parts", data.parts.filter((_, j) => j !== i))}><Ic.close width="15" height="15" /></button>
        </div>
      ))}
      <div className="part-add">
        <input className="inp inp--mono" list="pnlist" value={pn} onChange={(e) => setPn(e.target.value)} placeholder="P/N" />
        <datalist id="pnlist">{PART_LIB.map((p) => <option key={p.pn} value={p.pn}>{p.name}</option>)}</datalist>
        <input className="inp inp--mono" value={off} onChange={(e) => setOff(e.target.value)} placeholder="S/N OFF" />
        <input className="inp inp--mono" value={on} onChange={(e) => setOn(e.target.value)} placeholder="S/N ON" />
        <button className="part-addbtn" onClick={add}><Ic.plus width="18" height="18" /></button>
      </div>
    </div>
  );
}

function MultiPick({ lib, sel, set, icon: Icon, render }) {
  return (
    <div className="chiprow wrap">
      {lib.map((x) => {
        const on = sel.includes(x.id);
        return <Chip key={x.id} mono on={on} onClick={() => set(on ? sel.filter((s) => s !== x.id) : [...sel, x.id])}><Icon width="13" height="13" />{render(x)}</Chip>;
      })}
    </div>
  );
}

/* Searchable tool picker over the real Tool Inventory (ALL TOOLS).
   Shows each tool's store LOCATION + remaining qty so the tech can check the
   tool room straight from the work log. */
function ToolPicker({ sel, set }) {
  const [open, setOpen] = useS(false);
  const [q, setQ] = useS("");
  const lib = TOOL_LIB; // window.TOOL_LIB once the inventory has loaded
  const byId = (id) => lib.find((t) => t.id === id);
  const toggle = (id) => set(sel.includes(id) ? sel.filter((x) => x !== id) : [...sel, id]);
  const filtered = useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return [];
    const out = [];
    for (let i = 0; i < lib.length && out.length < 50; i++) {
      const t = lib[i];
      if ((t.id + " " + t.pn + " " + t.name + " " + t.loc).toLowerCase().includes(s)) out.push(t);
    }
    return out;
  }, [q, lib]);

  return (
    <>
      <div className="chiprow wrap">
        {sel.map((id) => {
          const t = byId(id);
          return (
            <button key={id} className="chip chip--on chip--mono toolchip" onClick={() => toggle(id)}>
              <Ic.tool width="13" height="13" />{t ? t.name : id}{t && t.loc ? <i className="toolchip-loc">{t.loc}</i> : null}<Ic.close width="12" height="12" />
            </button>
          );
        })}
        <button type="button" className="tool-add" onClick={() => setOpen(true)}><Ic.search width="15" height="15" />Search tools</button>
      </div>

      <Sheet open={open} onClose={() => setOpen(false)} title="Tool Inventory" full>
        <div className="searchbar searchbar--insheet">
          <Ic.search width="18" height="18" />
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="ค้นหา: ชื่อ, S/N, P/N, ตำแหน่ง" />
          {q && <button className="iconbtn" onClick={() => setQ("")}><Ic.close width="16" height="16" /></button>}
        </div>
        <div className="toollist">
          {filtered.map((t) => {
            const on = sel.includes(t.id);
            return (
              <button key={t.id + "|" + t.loc} className={"toolrow" + (on ? " toolrow--on" : "")} onClick={() => toggle(t.id)}>
                <span className="tool-knob">{on ? <Ic.check width="16" height="16" /> : <Ic.tool width="16" height="16" />}</span>
                <div className="tool-main">
                  <div className="tool-name">{t.name || "—"}</div>
                  <div className="tool-sub mono">S/N {t.id}{t.pn ? " · P/N " + t.pn : ""}{t.ata ? " · ATA " + t.ata : ""}</div>
                </div>
                <div className="tool-meta">
                  {t.loc ? <span className="tool-loc">{t.loc}</span> : <span className="tool-loc tool-loc--none">n/a</span>}
                  {t.qty ? <span className="tool-qty mono">Qty {t.qty}</span> : null}
                </div>
              </button>
            );
          })}
          {q && filtered.length === 0 && <div className="empty">No match for “{q}” — tool room may not have this</div>}
          {!q && <div className="tool-hint">พิมพ์เพื่อค้นจาก {lib.length.toLocaleString()} รายการในคลัง · ป้ายขวา = ตำแหน่งในห้อง tool + จำนวนคงเหลือ</div>}
        </div>
        <Btn full kind="primary" onClick={() => setOpen(false)} icon={<Ic.check width="18" height="18" />}>Done{sel.length ? ` (${sel.length})` : ""}</Btn>
      </Sheet>
    </>
  );
}

/* Standalone tool-inventory lookup — "do we have this tool, and where?" — usable
   before/independent of a work log. Read-only (no selection). */
function ToolSearchSheet({ open, onClose }) {
  const [q, setQ] = useS("");
  const lib = TOOL_LIB;
  const { rows, total } = useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return { rows: [], total: 0 };
    const rows = []; let total = 0;
    for (let i = 0; i < lib.length; i++) {
      const t = lib[i];
      if ((t.id + " " + t.pn + " " + t.name + " " + t.loc + " " + t.ata).toLowerCase().includes(s)) {
        total++; if (rows.length < 60) rows.push(t);
      }
    }
    return { rows, total };
  }, [q, lib]);

  return (
    <Sheet open={open} onClose={onClose} title="Search Tool Inventory" full>
      <p className="sheet-lead">เช็คก่อนเริ่มงานว่าห้อง tool มีอุปกรณ์นี้ไหม และอยู่ตำแหน่งไหน</p>
      <div className="searchbar searchbar--insheet">
        <Ic.search width="18" height="18" />
        <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="ชื่อ / S/N / P/N / ATA / ตำแหน่ง — เช่น torque, IDG, 28" />
        {q && <button className="iconbtn" onClick={() => setQ("")}><Ic.close width="16" height="16" /></button>}
      </div>
      {q && <div className="tool-count mono">{total ? `Found ${total.toLocaleString()}${total > rows.length ? ` · showing ${rows.length}` : ""}` : "Not in inventory"}</div>}
      <div className="toollist">
        {rows.map((t) => {
          const ok = t.qty && parseFloat(t.qty) > 0;
          return (
            <div key={t.id + "|" + t.loc} className="toolrow toolrow--ro">
              <span className={"tool-avail" + (ok ? " tool-avail--ok" : "")}>{ok ? <Ic.check width="15" height="15" /> : <Ic.tool width="15" height="15" />}</span>
              <div className="tool-main">
                <div className="tool-name">{t.name || "—"}</div>
                <div className="tool-sub mono">S/N {t.id}{t.pn ? " · P/N " + t.pn : ""}{t.ata ? " · ATA " + t.ata : ""}</div>
              </div>
              <div className="tool-meta">
                {t.loc ? <span className="tool-loc">{t.loc}</span> : <span className="tool-loc tool-loc--none">n/a</span>}
                {t.qty ? <span className="tool-qty mono">Qty {t.qty}</span> : null}
              </div>
            </div>
          );
        })}
        {q && rows.length === 0 && <div className="empty">No match for “{q}” — tool room may not have this</div>}
        {!q && <div className="tool-hint">พิมพ์เพื่อค้นจาก {lib.length.toLocaleString()} รายการในคลัง · ✓ เขียว = มีของพร้อม (คงเหลือ &gt; 0) · ป้ายขวา = ตำแหน่งห้อง tool</div>}
      </div>
    </Sheet>
  );
}

// Downscale a captured/selected image to a JPEG data-URL (keeps localStorage small).
function compressImage(file, maxDim = 1280, quality = 0.7) {
  return new Promise((resolve, reject) => {
    const url = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      let w = img.naturalWidth || img.width, h = img.naturalHeight || img.height;
      const m = Math.max(w, h);
      if (m > maxDim) { const s = maxDim / m; w = Math.round(w * s); h = Math.round(h * s); }
      const cv = document.createElement("canvas"); cv.width = w; cv.height = h;
      cv.getContext("2d").drawImage(img, 0, 0, w, h);
      URL.revokeObjectURL(url);
      try { resolve(cv.toDataURL("image/jpeg", quality)); } catch (e) { reject(e); }
    };
    img.onerror = (e) => { URL.revokeObjectURL(url); reject(e); };
    img.src = url;
  });
}

// Photo capture/attach — opens the real camera (or gallery) and stores each shot
// as a compressed data-URL. `photos` is an array of data-URL strings.
function PhotoPick({ photos = [], set }) {
  const [busy, setBusy] = useS(false);
  const onFiles = async (e) => {
    const files = Array.from(e.target.files || []);
    e.target.value = "";
    if (!files.length) return;
    setBusy(true);
    const next = photos.slice();
    for (const f of files) { try { next.push(await compressImage(f)); } catch (err) {} }
    set(next); setBusy(false);
  };
  return (
    <div className="photogrid">
      {photos.map((src, i) => (
        <div key={i} className="photo-thumb photo-thumb--img">
          <img src={src} alt={"photo " + (i + 1)} />
          <button className="photo-x" onClick={() => set(photos.filter((_, j) => j !== i))}><Ic.close width="12" height="12" /></button>
        </div>
      ))}
      <label className={"photo-add" + (busy ? " photo-add--busy" : "")}>
        <input type="file" accept="image/*" multiple hidden onChange={onFiles} />
        <Ic.camera width="22" height="22" /><span>{busy ? "Adding…" : "Add photo"}</span>
      </label>
    </div>
  );
}

/* ---------------------------- ATA SELECTOR (3 variants) ---------------------------- */
function AtaSelector({ open, onClose, variant, onPick }) {
  const [q, setQ] = useS("");
  const [showAll, setShowAll] = useS(false);
  const filtered = useMemo(() => ATA.filter((a) => (a.c + a.t + a.th).toLowerCase().includes(q.toLowerCase())), [q]);
  const pick = (c) => { onPick(c); onClose(); setQ(""); setShowAll(false); };

  const SearchList = (
    <>
      <div className="searchbar searchbar--insheet">
        <Ic.search width="18" height="18" />
        <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="ค้นหา ATA — เช่น fuel, 28, ฐานล้อ" />
        <button className="iconbtn"><Ic.mic width="18" height="18" /></button>
      </div>
      <div className="atalist">
        {filtered.map((a) => (
          <button key={a.c} className="atalist-row" onClick={() => pick(a.c)}>
            <span className="atalist-c mono">{a.c}</span>
            <span className="atalist-t">{a.t}<i>{a.th}</i></span>
            <Ic.chevron width="16" height="16" />
          </button>
        ))}
      </div>
    </>
  );

  const Grid = (
    <div className="atagrid">
      {ATA.map((a) => (
        <button key={a.c} className="atatile" onClick={() => pick(a.c)}>
          <span className="atatile-c mono">{a.c}</span>
          <span className="atatile-t">{a.t}</span>
          <span className="atatile-th">{a.th}</span>
        </button>
      ))}
    </div>
  );

  const Recent = showAll ? SearchList : (
    <div className="atarecent">
      <div className="ata-grp"><Ic.star width="14" height="14" />Favorites</div>
      <div className="chiprow wrap big">{ATA_FAV.map((c) => { const a = ATA.find((x) => x.c === c); return <button key={c} className="atabig" onClick={() => pick(c)}><b className="mono">{c}</b><span>{a.t}</span></button>; })}</div>
      <div className="ata-grp"><Ic.clock width="14" height="14" />Recent</div>
      <div className="chiprow wrap big">{ATA_RECENT.map((c) => { const a = ATA.find((x) => x.c === c); return <button key={c} className="atabig atabig--soft" onClick={() => pick(c)}><b className="mono">{c}</b><span>{a.t}</span></button>; })}</div>
      <button className="ata-showall" onClick={() => setShowAll(true)}><Ic.search width="16" height="16" />Search all ATA ({ATA.length})</button>
    </div>
  );

  return (
    <Sheet open={open} onClose={onClose} title="Select ATA Chapter" full>
      {variant === "grid" ? Grid : variant === "recent" ? Recent : SearchList}
    </Sheet>
  );
}

/* C/B Tip — per-computer quick reference (A320 CB Tip): pull/wait time + the
   C/B position(s) per system. Tap ✓ to drop a reset entry into the Work Log. */
function CBCompRef({ q, onLog }) {
  const lib = (window.CB_TIP && window.CB_TIP.length) ? window.CB_TIP : [];
  const s = (q || "").trim().toLowerCase();
  const list = s ? lib.filter((c) => (c.computer + " " + (c.sys || []).join(" ")).toLowerCase().includes(s)) : lib;
  return (
    <>
      <div className="cbg-count mono">{list.length} computers{s ? "" : " · pull/wait time + C/B position"}</div>
      <div className="cbtip-list">
        {list.map((c, i) => (
          <div key={c.computer + i} className="cbtip">
            <div className="cbtip-main">
              <div className="cbtip-name">{c.computer}</div>
              <div className="cbtip-cbs mono">{(c.sys || []).map((p, j) => <span key={j} className="cbtip-cb">{p}</span>)}</div>
            </div>
            <div className="cbtip-times">
              <span className="cbtip-t"><i>C/B OUT</i><b className="mono">{c.out || "—"}</b></span>
              <span className="cbtip-t cbtip-t--in"><i>C/B IN</i><b className="mono">{c.in || "—"}</b></span>
              <button className="cbtip-log" onClick={() => onLog(c)} title="Log this reset"><Ic.check width="16" height="16" /></button>
            </div>
          </div>
        ))}
        {s && list.length === 0 && <div className="empty">No computer matches “{q}”</div>}
        {!s && <div className="tool-hint">เวลา = ระยะที่ถือ C/B ออก (OUT) / รอหลังใส่กลับ (IN) · ป้าย = ตำแหน่ง C/B ต่อระบบ · อ้างอิง TSM เสมอ</div>}
      </div>
    </>
  );
}

/* ---------------------------- C/B RESET QUICK SHEET ---------------------------- */
// Manually-added C/B resets persist here so they accumulate in the searchable list.
const CB_CUSTOM_KEY = "aerolog.cb.custom";
function loadCBCustom() { try { const r = localStorage.getItem(CB_CUSTOM_KEY); if (r) { const a = JSON.parse(r); if (Array.isArray(a)) return a; } } catch (e) {} return []; }
function saveCBCustomLS(a) { try { localStorage.setItem(CB_CUSTOM_KEY, JSON.stringify(a)); } catch (e) {} }

function CBSheet({ open, onClose, onSave }) {
  const [q, setQ] = useS("");
  const [openKey, setOpenKey] = useS(null);
  const [note, setNote] = useS("");
  const [manual, setManual] = useS(false);
  const [mode, setMode] = useS("fault");   // "fault" (ECAM guide) | "comp" (CB Tip)
  const [m, setM] = useS({ ecam: "", cb: "", ata: "", note: "" });
  const [custom, setCustom] = useS(loadCBCustom);
  const logComp = (c) => {
    onSave({ ecam: "Computer reset: " + c.computer, computer: c.computer, ata: "—",
      procedure: `C/B ${(c.sys || []).join(" · ")}\nC/B OUT ${c.out || "—"} · C/B IN ${c.in || "—"}`, source: "CB-TIP" }, note);
    setNote(""); setQ("");
  };
  const setMf = (k, v) => setM((p) => ({ ...p, [k]: v }));
  const openManual = (ecam) => { setM((p) => ({ ...p, ecam: ecam || p.ecam })); setManual(true); };
  // Manual add → save into the C/B LIST (persisted, reusable) — not just a one-off log.
  const saveManual = () => {
    if (!m.ecam.trim() && !m.cb.trim()) return;
    const entry = { cid: "c" + Date.now(), ecam: m.ecam.trim() || "(manual)", computer: m.cb.trim(),
      ata: m.ata.trim() || "—", procedure: m.note.trim(), source: "CUSTOM" };
    const next = [entry, ...custom];
    setCustom(next); saveCBCustomLS(next);
    setM({ ecam: "", cb: "", ata: "", note: "" }); setManual(false); setQ("");
  };
  const removeCustom = (cid) => { const next = custom.filter((x) => x.cid !== cid); setCustom(next); saveCBCustomLS(next); };
  const baseLib = (window.CB_GUIDE && window.CB_GUIDE.length) ? window.CB_GUIDE : CB_LIB;
  const lib = custom.concat(baseLib);      // user's custom entries on top
  const s = q.trim().toLowerCase();
  const fkey = (f) => f.cid || ((f.ecam || f.id || "") + "|" + (f.computer || ""));
  const list = s ? lib.filter((f) => ((f.ecam || "") + " " + (f.computer || f.name || "") + " " + (f.ata || "") + " " + (f.procedure || f.note || "")).toLowerCase().includes(s)) : lib;
  const logIt = (f) => { onSave(f, note); setNote(""); setQ(""); setOpenKey(null); };
  return (
    <Sheet open={open} onClose={onClose} title="C/B Reset — ECAM guide" full>
      <p className="sheet-lead">ค้น ECAM fault ที่ขึ้น → ดูขั้นตอน reset (computer · panel · C/B · เวลา) แล้วบันทึกลง Work Log</p>
      <div className="cb-warn"><Ic.warn width="16" height="16" /><span>อ้างอิง AMM/TSM + นโยบาย C/B reset ของหน่วยงานเสมอ — บางตัวห้าม reset ขณะบิน หรือถ้า trip ซ้ำ</span></div>
      <div className="cb-mode">
        <button className={"cb-modebtn" + (mode === "fault" ? " cb-modebtn--on" : "")} onClick={() => setMode("fault")}>ECAM fault</button>
        <button className={"cb-modebtn" + (mode === "comp" ? " cb-modebtn--on" : "")} onClick={() => setMode("comp")}>Computer C/B ref</button>
      </div>
      <div className="searchbar searchbar--insheet">
        <Ic.search width="18" height="18" />
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={mode === "comp" ? "ค้น computer — เช่น ADIRU, FAC, FMGC, ELAC" : "ค้น ECAM / computer / ระบบ — เช่น FCU, FADEC, CAB PR"} />
        {q && <button className="iconbtn" onClick={() => setQ("")}><Ic.close width="16" height="16" /></button>}
      </div>
      {mode === "comp" ? <CBCompRef q={q} onLog={logComp} /> : <>
      <div className="cbg-count mono">{list.length} items{s ? "" : " · tap for reset steps"}</div>
      <div className="cbg-list">
        <div className={"cbg cbg--manual" + (manual ? " cbg--open" : "")}>
          <button className="cbg-head" onClick={() => (manual ? setManual(false) : openManual(s && list.length === 0 ? q : ""))}>
            <div className="cbg-h-main"><div className="cb-ecam"><span className="cb-ecam-tag cb-ecam-tag--add">+ Add</span>Add a C/B reset manually (not listed)</div></div>
            <span className={"cbg-chev" + (manual ? " cbg-chev--on" : "")}><Ic.chevron width="16" height="16" /></span>
          </button>
          {manual && (
            <div className="cbg-body">
              <Field label="ECAM fault"><input className="inp" value={m.ecam} onChange={(e) => setMf("ecam", e.target.value)} placeholder="เช่น ENG 2 OIL FILTER CLOG" /></Field>
              <Field label="C/B / Computer to reset"><input className="inp inp--mono" value={m.cb} onChange={(e) => setMf("cb", e.target.value)} placeholder="เช่น P6-5 FUEL PUMP LH · หรือ FCU 1 C/B B05" /></Field>
              <Field label="ATA (optional)"><input className="inp inp--mono" value={m.ata} onChange={(e) => setMf("ata", e.target.value)} placeholder="เช่น 28" /></Field>
              <Field label="Steps / Notes"><textarea className="inp inp--area" rows="3" value={m.note} onChange={(e) => setMf("note", e.target.value)} placeholder="panel · C/B · เวลา · found tripped ฯลฯ" /></Field>
              <Btn full kind="primary" onClick={saveManual} icon={<Ic.plus width="18" height="18" />}>Save to C/B list</Btn>
            </div>
          )}
        </div>
        {list.map((f) => {
          const k = fkey(f); const exp = openKey === k;
          const proc = f.procedure || f.note || "";
          return (
            <div key={k} className={"cbg" + (exp ? " cbg--open" : "")}>
              <button className="cbg-head" onClick={() => setOpenKey(exp ? null : k)}>
                <div className="cbg-h-main">
                  <div className="cb-ecam"><span className={"cb-ecam-tag" + (f.source === "MOC" ? " cb-ecam-tag--moc" : f.source === "CUSTOM" ? " cb-ecam-tag--custom" : "")}>{f.source || "ECAM"}</span>{f.ecam || f.name}</div>
                  {(f.computer || f.id) && <div className="cbg-comp mono">{f.computer || (f.id + " " + f.name)}</div>}
                </div>
                <AtaBadge code={f.ata || "—"} />
                <span className={"cbg-chev" + (exp ? " cbg-chev--on" : "")}><Ic.chevron width="16" height="16" /></span>
              </button>
              {exp && (
                <div className="cbg-body">
                  {proc && <div className="cbg-proc">{proc}</div>}
                  <textarea className="inp inp--area" rows="2" value={note} onChange={(e) => setNote(e.target.value)} placeholder="หมายเหตุ (เช่น found tripped, reset ops normal)" />
                  <div className="cbg-actions">
                    <Btn full kind="primary" onClick={() => logIt(f)} icon={<Ic.check width="18" height="18" />}>Log this reset</Btn>
                    {f.source === "CUSTOM" && <Btn kind="ghost" onClick={() => removeCustom(f.cid)} icon={<Ic.close width="16" height="16" />}>Delete</Btn>}
                  </div>
                </div>
              )}
            </div>
          );
        })}
        {s && list.length === 0 && (
          <div className="cb-empty">
            <div className="empty">“{q}” not in list</div>
            <Btn kind="primary" sm onClick={() => openManual(q)} icon={<Ic.plus width="16" height="16" />}>Add “{q}” manually</Btn>
          </div>
        )}
      </div>
      </>}
    </Sheet>
  );
}

/* Multiple AMM/TSM task references — type + Enter/＋ to add; tap a chip to remove. */
function AmmEditor({ list, set }) {
  const [v, setV] = useS("");
  const add = () => { const t = v.trim(); if (!t) return; if (!list.includes(t)) set([...list, t]); setV(""); };
  return (
    <div className="amm-ed">
      {list.length > 0 && (
        <div className="chiprow wrap">
          {list.map((a, i) => (
            <button key={i} type="button" className="chip chip--on chip--mono" onClick={() => set(list.filter((_, j) => j !== i))}>
              <Ic.doc width="12" height="12" />{a}<Ic.close width="12" height="12" />
            </button>
          ))}
        </div>
      )}
      <div className="amm-add">
        <input className="inp inp--mono" value={v} onChange={(e) => setV(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} placeholder="28-22-41-400-801" />
        <button type="button" className="part-addbtn" onClick={add}><Ic.plus width="18" height="18" /></button>
      </div>
    </div>
  );
}

/* ---------------------------- NEW LOG FLOW ---------------------------- */
const EMPTY = { reg: "", flight: null, ata: "", defect: "", action: "", amm: [], parts: [], tools: [], consumables: "", cb: [], photos: [], start: nowHM(), stop: "" };

// Map a saved log back into the editable form shape.
function logToForm(l) {
  return {
    reg: l.reg && l.reg !== "—" ? l.reg : "", flight: l.flight || null,
    ata: l.ata && l.ata !== "—" ? l.ata : "",
    defect: l.defect || "", action: l.action || "",
    amm: Array.isArray(l.amm) ? l.amm : (l.amm && l.amm !== "—" ? [l.amm] : []),
    parts: l.parts || [], tools: l.tools || [], consumables: l.consumables || "",
    cb: l.cb || [], photos: photoArr(l.photos),
    start: l.start || nowHM(), stop: (l.stop && l.stop !== l.start) ? l.stop : "",
  };
}

function NewLogFlow({ layout, ataVariant, attachedFlight, seed, editLog, onClose, onSave }) {
  const base = { ...EMPTY, reg: (window.FLEET && window.FLEET[0] ? window.FLEET[0].reg : "") };
  const init = editLog ? logToForm(editLog)
    : attachedFlight ? { ...base, reg: attachedFlight.reg, flight: attachedFlight.id }
    : seed ? { ...base, ata: seed.ata, defect: "Location: " + seed.pos + "\n" } : base;
  const [data, setData] = useS(init);
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const [ataOpen, setAtaOpen] = useS(false);
  const [step, setStep] = useS(0);

  const fields = {
    aircraft: <Field label="Aircraft / Flight" req><AircraftPick data={data} set={set} /></Field>,
    ata: <Field label="ATA Chapter" req><AtaPick data={data} onOpen={() => setAtaOpen(true)} /></Field>,
    defect: <Field label="Defect" req><textarea className="inp inp--area" rows="3" value={data.defect} onChange={(e) => set("defect", e.target.value)} placeholder="เช่น PFR fuel low pressure LH, pump pressure intermittent" /></Field>,
    action: <Field label="Action taken" req><textarea className="inp inp--area" rows="3" value={data.action} onChange={(e) => set("action", e.target.value)} placeholder="เช่น Removed/installed LH fuel boost pump iaw AMM…" /></Field>,
    amm: <Field label="Ref. AMM / TSM task(s)" hint="ใส่ได้หลายอัน — พิมพ์แล้วกด ＋ หรือ Enter"><AmmEditor list={Array.isArray(data.amm) ? data.amm : []} set={(v) => set("amm", v)} /></Field>,
    parts: <Field label="Parts (removed / installed)"><PartsEditor data={data} set={set} /></Field>,
    tools: <Field label="Tools / Equipment used" hint="ค้นจากคลังจริง — ดูตำแหน่งห้อง tool + จำนวนคงเหลือ"><ToolPicker sel={data.tools} set={(v) => set("tools", v)} /></Field>,
    consumables: <Field label="Consumables / other (free text)" hint="ของสิ้นเปลือง/เครื่องมือที่ไม่มีในคลัง — พิมพ์เอง"><textarea className="inp inp--area" rows="2" value={data.consumables} onChange={(e) => set("consumables", e.target.value)} placeholder="เช่น lockwire MS20995, grease, sealant PR-1422, tool ยืม / ไม่มีในคลัง..." /></Field>,
    cb: <Field label="Related C/B"><MultiPick lib={CB_LIB} sel={data.cb} set={(v) => set("cb", v)} icon={Ic.cb} render={(x) => x.id + " " + x.name} /></Field>,
    photos: <Field label="Photos" hint="ถ่ายจากกล้องหรือเลือกจากเครื่อง — แนบเข้า log"><PhotoPick photos={data.photos} set={(v) => set("photos", v)} /></Field>,
    time: <div className="timerow"><Field label="Start"><input className="inp inp--mono" value={data.start} onChange={(e) => set("start", e.target.value)} /></Field><Field label="Stop"><input className="inp inp--mono" value={data.stop} onChange={(e) => set("stop", e.target.value)} placeholder="--:--" /></Field></div>,
  };

  const finish = () => {
    const a = ATA.find((x) => x.c === data.ata);
    onSave({
      ...(editLog || {}),
      id: editLog ? editLog.id : "LOG-" + (2290 + Math.floor(Math.random() * 90)), reg: data.reg, ata: data.ata || "—", flight: data.flight,
      title: data.action ? data.action.slice(0, 38) : (a ? a.t : "New job"), th: editLog ? editLog.th : (a ? a.th : ""),
      defect: data.defect, action: data.action,
      amm: (Array.isArray(data.amm) && data.amm.length) ? data.amm : "—",
      consumables: (data.consumables || "").trim(),
      start: data.start, stop: data.stop || data.start, dur: editLog ? editLog.dur : "—",
      parts: data.parts, tools: data.tools, cb: data.cb, photos: photoArr(data.photos),
      status: editLog ? editLog.status : "draft", tech: "You",
    });
  };

  /* ---------- LAYOUT: long form ---------- */
  if (layout === "form") {
    return (
      <>
      <div className="screen-scroll entry">
        <TopBar title={editLog ? "Edit Work Log" : "New Work Log"} sub={editLog ? editLog.id : "One-page entry"} onBack={onClose} />
        <div className="entry-body">
          {fields.aircraft}{fields.ata}{fields.defect}{fields.action}{fields.amm}{fields.parts}{fields.tools}{fields.consumables}{fields.cb}{fields.photos}{fields.time}
        </div>
        <div className="scroll-pad" />
      </div>
      <div className="savebar"><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="primary" full onClick={finish} icon={<Ic.check width="18" height="18" />}>{editLog ? "Save changes" : "Save Log"}</Btn></div>
      <AtaSelector open={ataOpen} onClose={() => setAtaOpen(false)} variant={ataVariant} onPick={(c) => set("ata", c)} />
      </>
    );
  }

  /* ---------- LAYOUT: stepper & cards ---------- */
  const steps = [
    { label: "Aircraft", group: [fields.aircraft, fields.ata] },
    { label: "Defect", group: [fields.defect, fields.action, fields.amm] },
    { label: "Parts/Tools", group: [fields.parts, fields.tools, fields.consumables, fields.cb] },
    { label: "Photos/Time", group: [fields.photos, fields.time] },
    { label: "Review", group: [<ReviewCard key="r" data={data} />] },
  ];
  const isCards = layout === "cards";
  const cur = steps[step];
  return (
    <>
    <div className={"screen-scroll entry" + (isCards ? " entry--cards" : "")}>
      <TopBar title={isCards ? cur.label : (editLog ? "Edit Work Log" : "New Work Log")} sub={isCards ? `Card ${step + 1}/${steps.length}` : `Step ${step + 1} of ${steps.length}`} onBack={step === 0 ? onClose : () => setStep(step - 1)} />
      <div className="stepper-dots">{steps.map((s, i) => <button key={i} className={"dot" + (i === step ? " dot--on" : "") + (i < step ? " dot--done" : "")} onClick={() => setStep(i)}>{!isCards && <span>{s.label}</span>}</button>)}</div>
      <div className={"entry-body" + (isCards ? " cardface" : "")} key={step}>
        {cur.group.map((el, i) => React.cloneElement(el, { key: el.key != null ? el.key : i }))}
      </div>
      <div className="scroll-pad" />
    </div>
    <div className="savebar">
      {step > 0 && <Btn kind="ghost" onClick={() => setStep(step - 1)}>Back</Btn>}
      {step < steps.length - 1
        ? <Btn kind="primary" full onClick={() => setStep(step + 1)} icon={<Ic.arrowR width="18" height="18" />}>Next</Btn>
        : <Btn kind="primary" full onClick={finish} icon={<Ic.check width="18" height="18" />}>{editLog ? "Save changes" : "Save Log"}</Btn>}
    </div>
    <AtaSelector open={ataOpen} onClose={() => setAtaOpen(false)} variant={ataVariant} onPick={(c) => set("ata", c)} />
    </>
  );
}

function ReviewCard({ data }) {
  const a = ATA.find((x) => x.c === data.ata);
  return (
    <Card className="review">
      <div className="rev-head"><AtaBadge code={data.ata || "—"} big /><span className="mono rev-reg">{data.reg}{data.flight ? " · " + data.flight : ""}</span></div>
      <KV k="Defect" v={data.defect || "—"} /><KV k="Action" v={data.action || "—"} />
      <KV k="AMM" v={(Array.isArray(data.amm) ? (data.amm.length ? data.amm.join(", ") : "") : data.amm) || "—"} mono />
      <KV k="Parts" v={data.parts.length ? data.parts.map((p) => p.pn).join(", ") : "—"} mono />
      <KV k="Tools" v={data.tools.length + " items" + (data.consumables ? " + other" : "")} /><KV k="C/B" v={data.cb.length ? data.cb.join(", ") : "—"} mono />
      <KV k="Photos" v={photoCount(data.photos) + ""} /><KV k="Time" v={data.start + " – " + (data.stop || "--:--")} mono />
    </Card>
  );
}

Object.assign(window, { NewLogFlow, AtaSelector, CBSheet, CBCompRef, ReviewCard, ToolPicker, ToolSearchSheet, PhotoPick, compressImage });
