// New product / service form (Inventory)
function Switch({ label, value, onChange, hint }) {
  return (
    <button type="button" className="switchrow" onClick={() => onChange(!value)} aria-pressed={value}>
      <span className={"sw" + (value ? " on" : "")}><i></i></span>
      <span className="switchrow-text">
        <b>{label}</b>
        {hint ? <small>{hint}</small> : null}
      </span>
    </button>
  );
}

const PF_CATS = {
  Furniture: ["Seating", "Tables & desks", "Storage", "Bedroom"],
  Hardware: ["Handles & knobs", "Hinges", "Fasteners", "Rails"],
  Lighting: ["Ceiling", "Wall", "Floor & table", "Outdoor"],
  Textiles: ["Rugs & runners", "Curtains", "Cushions", "Upholstery fabric"]
};
const PF_SERVICE_CATS = {
  "Assembly & installation": ["Furniture assembly", "Lighting installation", "Curtain fitting"],
  "Delivery": ["Standard delivery", "White-glove delivery"],
  "Design & consulting": ["Interior consultation", "Space planning"],
  "Repair & maintenance": ["Furniture repair", "Reupholstery"]
};
const PF_BRANDS = ["Northgate Own", "Fjord & Pine", "Calder Supply Co", "Lumen Works", "Aria Textiles"];
const PF_UNITS = ["Piece", "Pair", "Set", "Meter", "Kilogram", "Roll"];
const PF_SVC_UNITS = ["Hour", "Visit", "Job", "Square meter"];

/* legacy inline-add select replaced by SearchSelect (components.jsx) */

function NewItemModal({ open, onClose, onCreate, warehouses, onCreateWarehouse }) {
  const { useState, useEffect, useRef } = React;
  const blank = {
    type: "product", name: "", cat: "", sub: "", brand: "", wh: "",
    price: "", tax: "5", minPrice: "", cost: "",
    unit: "Piece", minQty: "", order: "", points: "",
    active: true, byWeight: false, desc: ""
  };
  const [f, setF] = useState(blank);
  const [barcodes, setBarcodes] = useState([{ name: "", code: "" }]);
  const [images, setImages] = useState([]); // {url, name}
  const [mainImg, setMainImg] = useState(0);
  const [errs, setErrs] = useState({});
  const fileRef = useRef(null);

  // user-extendable lists (persist while the app is open)
  const [brands, setBrands] = useState(PF_BRANDS);
  const [prodCats, setProdCats] = useState(PF_CATS);
  const [svcCats, setSvcCats] = useState(PF_SERVICE_CATS);
  const [prodUnits, setProdUnits] = useState(PF_UNITS);
  const [svcUnits, setSvcUnits] = useState(PF_SVC_UNITS);

  useEffect(() => {
    if (open) { setF({ ...blank, wh: (warehouses && warehouses[0]) || "Central" }); setBarcodes([{ name: "", code: "" }]); setImages([]); setMainImg(0); setErrs({}); }
  }, [open]);

  if (!open) return null;
  const isSvc = f.type === "service";
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const cats = isSvc ? svcCats : prodCats;
  const setCats = isSvc ? setSvcCats : setProdCats;
  const units = isSvc ? svcUnits : prodUnits;
  const setUnits = isSvc ? setSvcUnits : setProdUnits;
  const num = (v) => { const n = parseFloat(v); return isNaN(n) ? 0 : n; };

  const price = num(f.price), taxPct = num(f.tax);
  const afterTax = price * (1 + taxPct / 100);
  const setAfterTax = (v) => {
    const n = num(v);
    set("price", taxPct >= 0 ? String(+(n / (1 + taxPct / 100)).toFixed(2)) : f.price);
  };
  const margin = price > 0 && num(f.cost) > 0 ? Math.round(((price - num(f.cost)) / price) * 100) : null;

  const addFiles = (files) => {
    const next = Array.from(files).filter((x) => x.type.startsWith("image/"))
      .map((x) => ({ url: URL.createObjectURL(x), name: x.name }));
    if (next.length) setImages((prev) => [...prev, ...next]);
  };
  const removeImg = (i) => {
    setImages((prev) => prev.filter((_, j) => j !== i));
    setMainImg((m) => (i === m ? 0 : i < m ? m - 1 : m));
  };

  const validate = () => {
    const e = {};
    if (!f.name.trim()) e.name = T("pf.errName");
    if (!f.cat) e.cat = T("pf.errCategory");
    if (price <= 0) e.price = T("pf.errPrice");
    if (!isSvc && num(f.cost) <= 0) e.cost = T("pf.errCost");
    if (f.minPrice && num(f.minPrice) > price) e.minPrice = T("pf.errMinPrice");
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const save = () => {
    if (!validate()) return;
    onCreate({
      sku: (isSvc ? "SV-" : "NG-") + (7000 + Math.floor(Math.random() * 900)),
      type: f.type, name: f.name.trim(), cat: f.cat, sub: f.sub, brand: f.brand,
      wh: isSvc ? "—" : (f.wh || "Central"),
      stock: isSvc ? null : 0,
      reorder: isSvc ? null : (num(f.minQty) || 0),
      cost: num(f.cost), price, tax: taxPct, priceAfterTax: +afterTax.toFixed(2),
      minPrice: num(f.minPrice), unit: f.unit, order: num(f.order), points: num(f.points),
      active: f.active, byWeight: f.byWeight, desc: f.desc,
      barcodes: barcodes.map((b) => ({ name: b.name.trim(), code: b.code.trim() })).filter((b) => b.code),
      images: images.map((x) => x.url), mainImage: images[mainImg] ? images[mainImg].url : null
    });
  };

  return (
    <Modal open={open} onClose={onClose} width={720}
      title={isSvc ? T("pf.newService") : T("pf.newProduct")}
      sub={T("pf.catalogItemSub")}
      footer={
        <div className="btnrow">
          <Btn variant="primary" icon="check" onClick={save}>{isSvc ? T("pf.createService") : T("pf.createProduct")}</Btn>
          <Btn onClick={onClose}>{T("common.cancel")}</Btn>
        </div>
      }>

      <div className="seg" role="tablist">
        <button className={"seg-btn" + (!isSvc ? " on" : "")} onClick={() => setF((p) => ({ ...p, type: "product", cat: "", sub: "", unit: "Piece" }))}>
          <Icon name="box" size={15} />{T("mfg.product")}
        </button>
        <button className={"seg-btn" + (isSvc ? " on" : "")} onClick={() => setF((p) => ({ ...p, type: "service", cat: "", sub: "", unit: "Hour", byWeight: false }))}>
          <Icon name="spark" size={15} />{T("pf.service")}
        </button>
      </div>

      <div className="formsec">{T("pf.basics")}</div>
      <div className="formgrid">
        <Field label={T("common.name")} error={errs.name}>
          <Input placeholder={isSvc ? T("pf.serviceNamePlaceholder") : T("pf.productNamePlaceholder")}
            value={f.name} onChange={(e) => set("name", e.target.value)} />
        </Field>
        <Field label={T("pf.brand")}>
          <SearchSelect options={brands} placeholder={T("pf.chooseBrand")} addLabel={T("pf.addBrand")}
            value={f.brand} onChange={(v) => set("brand", v)}
            onCreate={(v) => { if (!brands.includes(v)) setBrands((b) => [...b, v]); set("brand", v); notify(T("pf.brandAdded", { name: v })); }} />
        </Field>
        <Field label={T("common.category")} error={errs.cat}>
          <SearchSelect options={Object.keys(cats)} placeholder={T("common.choose")} addLabel={T("pf.addCategory")}
            value={f.cat} onChange={(v) => setF((p) => ({ ...p, cat: v, sub: "" }))}
            onCreate={(v) => { setCats((c) => (c[v] ? c : { ...c, [v]: [] })); setF((p) => ({ ...p, cat: v, sub: "" })); notify(T("pf.categoryAdded", { name: v })); }} />
        </Field>
        <Field label={T("pf.subcategory")}>
          <SearchSelect options={f.cat ? (cats[f.cat] || []) : []} disabled={!f.cat}
            placeholder={f.cat ? T("common.choose") : T("pf.pickCategoryFirst")} addLabel={T("pf.addSubcategory")}
            value={f.sub} onChange={(v) => set("sub", v)}
            onCreate={(v) => { setCats((c) => ({ ...c, [f.cat]: (c[f.cat] || []).includes(v) ? c[f.cat] : [...(c[f.cat] || []), v] })); set("sub", v); notify(T("pf.subcategoryAdded", { name: v, cat: TV(f.cat) })); }} />
        </Field>
      </div>

      <div className="formsec">{T("pf.pricing")}</div>
      <div className="formgrid three">
        <Field label={T("common.price")} error={errs.price}>
          <Input type="number" min="0" step="0.5" placeholder="0.00" value={f.price} onChange={(e) => set("price", e.target.value)} />
        </Field>
        <Field label={T("acct.taxPercent")}>
          <Input type="number" min="0" step="0.5" value={f.tax} onChange={(e) => set("tax", e.target.value)} />
        </Field>
        <Field label={T("pf.priceAfterTax")}>
          <Input type="number" min="0" step="0.5" value={f.price === "" ? "" : String(+afterTax.toFixed(2))}
            onChange={(e) => setAfterTax(e.target.value)} />
        </Field>
        <Field label={T("inv.minimumPrice")} error={errs.minPrice}>
          <Input type="number" min="0" step="0.5" placeholder={T("pf.minPricePlaceholder")} value={f.minPrice} onChange={(e) => set("minPrice", e.target.value)} />
        </Field>
        <Field label={T("pf.cost")} error={errs.cost}>
          <Input type="number" min="0" step="0.5" placeholder="0.00" value={f.cost} onChange={(e) => set("cost", e.target.value)} />
        </Field>
        <Field label={T("inv.margin")}>
          <div className="calcfield mono">{margin === null ? "—" : margin + "%"}</div>
        </Field>
      </div>

      <div className="formsec">{isSvc ? T("pf.details") : T("pf.stockAndSelling")}</div>
      <div className="formgrid three">
        <Field label={T("pf.unit")}>
          <SearchSelect options={units} addLabel={T("pf.addUnit")}
            value={f.unit} onChange={(v) => set("unit", v)}
            onCreate={(v) => { if (!units.includes(v)) setUnits((u) => [...u, v]); set("unit", v); notify(T("pf.unitAdded", { name: v })); }} />
        </Field>
        {!isSvc ? (
          <Field label={T("inv.warehouse")}>
            <SearchSelect options={warehouses || []} addLabel={T("pf.addWarehouse")}
              value={f.wh} onChange={(v) => set("wh", v)}
              onCreate={(v) => { if (onCreateWarehouse && onCreateWarehouse(v)) set("wh", v.trim()); }} />
          </Field>
        ) : null}
        {!isSvc ? (
          <Field label={T("pf.minimumQuantity")}>
            <Input type="number" min="0" placeholder={T("inv.reorderPoint")} value={f.minQty} onChange={(e) => set("minQty", e.target.value)} />
          </Field>
        ) : null}
        <Field label={T("pf.sortOrder")}>
          <Input type="number" min="0" placeholder={T("pf.sortOrderPlaceholder")} value={f.order} onChange={(e) => set("order", e.target.value)} />
        </Field>
        <Field label={T("inv.earnPoints")}>
          <Input type="number" min="0" placeholder={T("pf.pointsPlaceholder")} value={f.points} onChange={(e) => set("points", e.target.value)} />
        </Field>
      </div>
      <div className="switches">
        <Switch label={TV("Active")} hint={T("pf.activeHint")} value={f.active} onChange={(v) => set("active", v)} />
        {!isSvc ? (
          <Switch label={T("inv.soldByWeight")} hint={T("pf.byWeightHint")} value={f.byWeight} onChange={(v) => set("byWeight", v)} />
        ) : null}
      </div>

      <div className="formsec">{T("inv.barcodes")}</div>
      <div className="bclist">
        {barcodes.map((b, i) => (
          <div key={i} className="bc-row">
            <span className="bc-ico mono">{String(i + 1).padStart(2, "0")}</span>
            <Input placeholder={i === 0 ? T("pf.barcodeNamePlaceholder1") : T("pf.barcodeNamePlaceholder2")} style={{ flex: "0 0 34%" }}
              value={b.name} onChange={(e) => setBarcodes((bs) => bs.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)))} />
            <Input placeholder={T("pf.barcodeCodePlaceholder")}
              value={b.code} onChange={(e) => setBarcodes((bs) => bs.map((x, j) => (j === i ? { ...x, code: e.target.value } : x)))} />
            {barcodes.length > 1 ? (
              <button className="iconbtn" onClick={() => setBarcodes((bs) => bs.filter((_, j) => j !== i))} aria-label={T("pf.removeBarcode")}>
                <Icon name="x" size={15} />
              </button>
            ) : null}
          </div>
        ))}
        <Btn small icon="plus" onClick={() => setBarcodes((bs) => [...bs, { name: "", code: "" }])}>{T("pf.addBarcode")}</Btn>
      </div>

      <div className="formsec">{T("pf.images")}</div>
      <div className="imgs">
        {images.map((img, i) => (
          <div key={img.url} className={"img-tile" + (i === mainImg ? " main" : "")} onClick={() => setMainImg(i)}
            title={i === mainImg ? T("pf.mainImage") : T("pf.setAsMainImage")}>
            <img src={img.url} alt={img.name} />
            {i === mainImg ? <span className="img-main">{T("pf.main")}</span> : null}
            <button className="img-x" onClick={(e) => { e.stopPropagation(); removeImg(i); }} aria-label={T("pf.removeImage")}>
              <Icon name="x" size={12} stroke={2.4} />
            </button>
          </div>
        ))}
        <button className="img-add" onClick={() => fileRef.current && fileRef.current.click()}>
          <Icon name="plus" size={18} />
          <span>{T("pf.addImages")}</span>
        </button>
        <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: "none" }}
          onChange={(e) => { addFiles(e.target.files); e.target.value = ""; }} />
      </div>
      {images.length > 1 ? <p className="formhint">{T("pf.clickImageHint")}</p> : null}

      <div className="formsec">{T("common.description")}</div>
      <Field label="">
        <textarea className="input area" rows="3" placeholder={isSvc ? T("pf.serviceDescPlaceholder") : T("pf.productDescPlaceholder")}
          value={f.desc} onChange={(e) => set("desc", e.target.value)}></textarea>
      </Field>
    </Modal>
  );
}
window.NewItemModal = NewItemModal;
