/* Itemised investment categories — expandable detail rows + checklist dropdown */
const { useState: useStateID } = React;

const INV_SUGGEST = {
  renovation: {
    en: ["Construction & structural work", "Electrical & plumbing", "Flooring & painting", "Air conditioning", "Signage", "Design & architect fees"],
    th: ["งานก่อสร้างและโครงสร้าง", "งานไฟฟ้าและประปา", "พื้นและสี", "เครื่องปรับอากาศ", "ป้าย", "ค่าออกแบบและสถาปนิก"],
  },
  equipment: {
    en: ["Refrigerator", "Freezer", "Stove / burner range", "Oven", "Ventilation hood", "Prep tables & sinks", "Dishwasher", "Cookware & small wares", "Coffee machine"],
    th: ["ตู้เย็น", "ตู้แช่แข็ง", "เตา/เตาแก๊ส", "เตาอบ", "เครื่องดูดควัน", "โต๊ะเตรียมอาหารและอ่างล้าง", "เครื่องล้างจาน", "เครื่องครัวและอุปกรณ์เล็ก", "เครื่องชงกาแฟ"],
  },
  furniture: {
    en: ["Dining tables", "Chairs", "Bar stools", "Lighting", "Décor & plants", "Tableware & glassware"],
    th: ["โต๊ะรับประทานอาหาร", "เก้าอี้", "เก้าอี้บาร์", "ไฟส่องสว่าง", "ของตกแต่งและต้นไม้", "ภาชนะและแก้ว"],
  },
  deposit: {
    en: ["Security deposit", "Advance rent", "Key money"],
    th: ["เงินมัดจำ", "ค่าเช่าล่วงหน้า", "ค่าแป๊ะเจี๊ยะ"],
  },
  licenses: {
    en: ["Business registration", "Food licence", "Alcohol licence", "Signage permit"],
    th: ["จดทะเบียนธุรกิจ", "ใบอนุญาตอาหาร", "ใบอนุญาตแอลกอฮอล์", "ใบอนุญาตป้าย"],
  },
  management: {
    en: ["POS system", "Accounting software", "Website & online presence", "Delivery platform setup", "Workspace / software subscriptions", "Insurance (first year)"],
    th: ["ระบบ POS", "โปรแกรมบัญชี", "เว็บไซต์และช่องทางออนไลน์", "การตั้งค่าแพลตฟอร์มเดลิเวอรี่", "ค่าสมัครสมาชิกซอฟต์แวร์", "ประกัน (ปีแรก)"],
  },
  inventory: {
    en: ["Food stock", "Beverage stock", "Dry goods", "Packaging & takeaway"],
    th: ["สต๊อกวัตถุดิบ", "สต๊อกเครื่องดื่ม", "ของแห้ง", "บรรจุภัณฑ์และกล่องซื้อกลับ"],
  },
  reserve: {
    en: ["Rent buffer", "Wage buffer", "Emergency fund"],
    th: ["เงินสำรองค่าเช่า", "เงินสำรองค่าแรง", "กองทุนฉุกเฉิน"],
  },
};

const COST_SUGGEST = {
  staff: {
    en: ["Chef", "Cook", "Kitchen assistant", "Server / waiter", "Cashier", "Manager", "Cleaner", "Your own salary"],
    th: ["เชฟ", "พ่อครัว/แม่ครัว", "ผู้ช่วยครัว", "พนักงานเสิร์ฟ", "แคชเชียร์", "ผู้จัดการ", "แม่บ้าน", "เงินเดือนของคุณเอง"],
  },
  rent: {
    en: ["Base rent", "Common area fees", "Storage rental"],
    th: ["ค่าเช่าหลัก", "ค่าส่วนกลาง", "ค่าเช่าที่เก็บของ"],
  },
  utilities: {
    en: ["Electricity", "Water", "Gas", "Internet & phone", "Waste collection"],
    th: ["ค่าไฟ", "ค่าน้ำ", "ค่าแก๊ส", "อินเทอร์เน็ตและโทรศัพท์", "ค่าเก็บขยะ"],
  },
  marketing: {
    en: ["Online ads", "Promotions & discounts", "Content & photography", "Loyalty program"],
    th: ["โฆษณาออนไลน์", "โปรโมชั่นและส่วนลด", "คอนเทนต์และถ่ายภาพ", "โปรแกรมสะสมแต้ม"],
  },
  management: {
    en: ["Insurance", "Accounting service", "POS subscription", "Printer / equipment rental", "Software subscriptions", "Bank & card fees"],
    th: ["ประกัน", "บริการบัญชี", "ค่าสมัคร POS", "ค่าเช่าเครื่องพิมพ์/อุปกรณ์", "ค่าสมัครสมาชิกซอฟต์แวร์", "ค่าธรรมเนียมธนาคารและบัตร"],
  },
  other: {
    en: ["Delivery platform fees", "Cleaning supplies", "Repairs & maintenance", "Uniforms", "Miscellaneous"],
    th: ["ค่าธรรมเนียมแพลตฟอร์มเดลิเวอรี่", "อุปกรณ์ทำความสะอาด", "ซ่อมแซมและบำรุงรักษา", "เครื่องแบบพนักงาน", "เบ็ดเตล็ด"],
  },
  taxes: {
    en: ["VAT set-aside", "Corporate income tax", "Social security (employer)", "Withholding tax", "Accounting & filing"],
    th: ["เงินกัน VAT", "ภาษีนิติบุคคล", "ประกันสังคม (นายจ้าง)", "ภาษีหัก ณ ที่จ่าย", "ค่าบัญชีและยื่นภาษี"],
  },
};

function MiniNum({ value, onChange, width = 92, prefix, suffix, placeholder = "0" }) {
  const [focus, setFocus] = useStateID(false);
  const [draft, setDraft] = useStateID("");
  const display = focus ? draft : value ? fmt(value) : "";
  return (
    <label style={{
      display: "flex", alignItems: "center", gap: 4, width, padding: "8px 10px",
      background: focus ? "var(--surface)" : "var(--surface-2)",
      border: `1.5px solid ${focus ? "var(--accent)" : "var(--border)"}`,
      borderRadius: 9, cursor: "text", transition: "border-color .15s", flexShrink: 0,
    }}>
      {prefix && <span style={{ color: "var(--faint)", fontSize: 12, fontWeight: 600 }}>{prefix}</span>}
      <input inputMode="numeric" value={display} placeholder={placeholder}
        onFocus={() => { setFocus(true); setDraft(value ? String(value) : ""); }}
        onBlur={() => setFocus(false)}
        onChange={(e) => { onChange(parseNum(e.target.value)); setDraft(e.target.value.replace(/[^0-9.]/g, "")); }}
        style={{ flex: 1, minWidth: 0, textAlign: "right", border: "none", outline: "none", background: "transparent", fontSize: 14, fontWeight: 600, color: "var(--ink)", fontVariantNumeric: "tabular-nums", padding: 0 }} />
      {suffix && <span style={{ color: "var(--faint)", fontSize: 11.5, fontWeight: 500 }}>{suffix}</span>}
    </label>
  );
}

function InvItemRow({ item, onChange, onRemove }) {
  const { t } = useLang();
  const lineTotal = (item.qty || 0) * (item.price || 0);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 62px 104px 92px 26px", gap: 8, alignItems: "center", padding: "5px 0" }}>
      <input value={item.name} placeholder={t("inv.itemNamePh")} autoFocus={item.name === ""}
        onChange={(e) => onChange({ name: e.target.value })}
        style={{ minWidth: 0, border: "none", outline: "none", background: "transparent", borderBottom: "1px dashed var(--border-strong)", fontFamily: "inherit", fontSize: 14, fontWeight: 500, color: "var(--ink)", padding: "6px 0" }} />
      <MiniNum width={62} value={item.qty} onChange={(v) => onChange({ qty: v })} placeholder="1" />
      <MiniNum width={104} prefix="฿" value={item.price} onChange={(v) => onChange({ price: v })} />
      <span className="serif-fig" style={{ textAlign: "right", fontSize: 15, color: "var(--ink)" }}>{lineTotal ? fmtBaht(lineTotal) : "—"}</span>
      <button onClick={onRemove} title="Remove item"
        style={{ width: 26, height: 26, border: "none", borderRadius: 7, background: "transparent", color: "var(--faint)", cursor: "pointer", fontSize: 15, lineHeight: 1, display: "grid", placeItems: "center" }}
        onMouseEnter={(e) => { e.currentTarget.style.background = "var(--red-tint)"; e.currentTarget.style.color = "var(--red)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--faint)"; }}>×</button>
    </div>
  );
}

function AddItemPicker({ suggestions, used, onAdd }) {
  const { t } = useLang();
  return (
    <select value="" onChange={(e) => { const v = e.target.value; if (v === "__custom") onAdd(""); else if (v) onAdd(v); }}
      style={{
        width: "100%", marginTop: 10, padding: "10px 12px", borderRadius: 10,
        border: "1.5px dashed var(--border-strong)", background: "var(--surface)",
        fontFamily: "inherit", fontSize: 14, fontWeight: 600, color: "var(--accent)",
        cursor: "pointer", outline: "none", appearance: "auto",
      }}>
      <option value="" disabled>{t("inv.addItem")}</option>
      {suggestions.map((s) => (
        <option key={s} value={s} disabled={used.has(s)}>{used.has(s) ? "✓ " : ""}{s}</option>
      ))}
      <option value="__custom">{t("inv.typeOwn")}</option>
    </select>
  );
}

function InvCategory({ label, hint, value, items, onValue, onItems, last, suggestions, meta }) {
  const { t } = useLang();
  const [open, setOpen] = useStateID(false);
  const itemized = items.length > 0;
  const total = itemized ? items.reduce((a, it) => a + (it.qty || 0) * (it.price || 0), 0) : value;
  const upd = (id, patch) => onItems(items.map((it) => (it.id === id ? { ...it, ...patch } : it)));
  const remove = (id) => onItems(items.filter((it) => it.id !== id));
  const add = (name) => onItems([...items, { id: Date.now() + Math.random(), name, qty: 1, price: 0 }]);
  const used = new Set(items.map((i) => i.name));
  return (
    <div style={{ borderBottom: last ? "none" : "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "15px 0" }}>
        <button onClick={() => setOpen(!open)} aria-expanded={open} title={open ? "Collapse" : "Add item details"}
          style={{ width: 26, height: 26, flexShrink: 0, border: "1px solid var(--border)", borderRadius: 8, background: open ? "var(--accent-tint)" : "var(--surface-2)", cursor: "pointer", display: "grid", placeItems: "center", padding: 0 }}>
          <span style={{ display: "block", color: "var(--accent)", fontSize: 13, fontWeight: 700, transform: open ? "rotate(90deg)" : "none", transition: "transform .18s" }}>›</span>
        </button>
        <div style={{ flex: 1, minWidth: 0, cursor: "pointer" }} onClick={() => setOpen(!open)}>
          <div style={{ fontWeight: 600, fontSize: 15.5, letterSpacing: "-.005em" }}>{label}</div>
          <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 3, lineHeight: 1.4 }}>
            {itemized ? <span style={{ color: "var(--accent)", fontWeight: 600 }}>{items.length}{t("inv.itemized")}</span> : hint}
          </div>
        </div>
        <div style={{ flexShrink: 0 }}>
          {itemized ? (
            <button onClick={() => setOpen(!open)} style={{ border: "none", background: "transparent", cursor: "pointer", textAlign: "right", padding: "4px 2px", fontFamily: "inherit" }}>
              <span className="serif-fig" style={{ fontSize: 24, color: "var(--ink)" }}>{fmtBaht(total)}</span>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--faint)", marginTop: 2 }}>{t("inv.autoSummed")}{meta ? ` · ${meta}` : ""}</div>
            </button>
          ) : (
            <div>
              <Amount value={value} onChange={onValue} />
              {meta && <div className="mono" style={{ fontSize: 9.5, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--faint)", marginTop: 5, textAlign: "right" }}>{meta}</div>}
            </div>
          )}
        </div>
      </div>
      {open && (
        <div style={{ margin: "0 0 16px 38px", padding: "14px 16px", background: "var(--surface-2)", borderRadius: 12, border: "1px solid var(--border)", animation: "fadeIn .25s" }}>
          {!itemized && (
            <div style={{ fontSize: 13.5, color: "var(--muted)", lineHeight: 1.5, marginBottom: 4 }}>
              {t("inv.notSureTotal")}
            </div>
          )}
          {itemized && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 62px 104px 92px 26px", gap: 8, paddingBottom: 4 }} className="mono">
              {[t("inv.itemHeader"), t("inv.qtyHeader"), t("inv.priceHeader"), t("inv.totalHeader"), ""].map((h, i) => (
                <span key={i} style={{ fontSize: 9.5, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--faint)", textAlign: i >= 1 && i <= 3 ? "right" : "left" }}>{h}</span>
              ))}
            </div>
          )}
          {items.map((it) => (
            <InvItemRow key={it.id} item={it} onChange={(p) => upd(it.id, p)} onRemove={() => remove(it.id)} />
          ))}
          <AddItemPicker suggestions={suggestions} used={used} onAdd={add} />
          {itemized && (
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
              <button onClick={() => { onValue(total); onItems([]); setOpen(false); }}
                style={{ border: "none", background: "transparent", cursor: "pointer", fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "var(--muted)", textDecoration: "underline", padding: 0 }}>
                {t("inv.backToSingle")}
              </button>
              <span style={{ fontSize: 13.5, color: "var(--muted)" }}>{t("inv.subtotal")}<strong className="serif-fig" style={{ fontSize: 16, color: "var(--ink)", fontWeight: 400 }}>{fmtBaht(total)}</strong></span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function SpaceCard({ space, onChange }) {
  const { t } = useLang();
  const cap = (txt) => <div className="mono" style={{ fontSize: 9.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--faint)", marginBottom: 5 }}>{txt}</div>;
  return (
    <div style={{ marginTop: 16, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", padding: "18px 26px", boxShadow: "var(--shadow)", display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
      <div style={{ flex: 1, minWidth: 220 }}>
        <div style={{ fontWeight: 600, fontSize: 15.5 }}>{t("fin.yourSpace")}<span style={{ color: "var(--faint)", fontWeight: 500, fontSize: 13 }}>{t("fin.optional")}</span></div>
        <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 3, lineHeight: 1.4 }}>{t("fin.spaceDesc")}</div>
      </div>
      <div style={{ display: "flex", gap: 12, flexShrink: 0 }}>
        <div>{cap(t("fin.shopArea"))}<MiniNum width={104} value={space.shopSqm} onChange={(v) => onChange({ shopSqm: v })} suffix="m²" /></div>
        <div>{cap(t("fin.kitchenArea"))}<MiniNum width={104} value={space.kitchenSqm} onChange={(v) => onChange({ kitchenSqm: v })} suffix="m²" /></div>
      </div>
    </div>
  );
}

Object.assign(window, { INV_SUGGEST, COST_SUGGEST, MiniNum, InvCategory, SpaceCard });
