/* Kay Construction — Expenses + Company Settings. */

const EXP_CATEGORIES = ["material", "upah", "sewa alat", "transport", "perizinan", "lainnya"];

function ExpenseForm({ expense, onClose, defaultProject }) {
  const [lang] = useLang();
  const projects = S.all("projects");
  const [f, setF] = useState(expense || { projectId: defaultProject || (projects[0] ? projects[0].id : ""), date: S.todayISO(), category: "material", description: "", amount: 0, supplier: "" });
  const set = (k, v) => setF((o) => ({ ...o, [k]: v }));
  const save = () => { if (!f.description.trim() || !f.amount) return alert(lang === "en" ? "Description and amount required" : "Deskripsi dan jumlah wajib diisi"); S.upsert("expenses", f); onClose(); };
  return (
    <Modal title={expense ? t("common.edit") : t("exp.new")} size="lg" onClose={onClose}
      footer={<><Button variant="ghost" onClick={onClose}>{t("common.cancel")}</Button><Button variant="primary" icon="check" onClick={save}>{t("common.save")}</Button></>}>
      <div className="form-grid">
        <Field label={t("common.project")}>
          <Select value={f.projectId} onChange={(e) => set("projectId", e.target.value)}>
            {projects.map((p) => <option key={p.id} value={p.id}>{p.code} · {p.name}</option>)}
          </Select>
        </Field>
        <Field label={t("common.category")}>
          <Select value={f.category} onChange={(e) => set("category", e.target.value)}>{EXP_CATEGORIES.map((c) => <option key={c} value={c}>{t("exp.cat." + c)}</option>)}</Select>
        </Field>
        <Field label={t("common.date")}><Input type="date" value={f.date} onChange={(e) => set("date", e.target.value)} /></Field>
        <Field label={t("common.amount")}><MoneyInput value={f.amount} onChange={(v) => set("amount", v)} /></Field>
        <Field label={t("common.description")} full><Input value={f.description} onChange={(e) => set("description", e.target.value)} /></Field>
        <Field label={t("exp.supplier")} optional full><Input value={f.supplier} onChange={(e) => set("supplier", e.target.value)} /></Field>
        <div className="field full">
          <label>{t("exp.receipt")} <span className="opt">· {t("common.optional")}</span></label>
          <div className="row" style={{ gap: 12, flexWrap: "wrap" }}>
            {f.receiptImage
              ? <div style={{ position: "relative" }}>
                  <img src={f.receiptImage} alt="" style={{ width: 88, height: 88, objectFit: "cover", borderRadius: "var(--r-sm)", border: "1px solid var(--line)" }} />
                  <Button variant="ghost" size="sm" icon="trash" onClick={() => set("receiptImage", "")} style={{ position: "absolute", top: 2, right: 2, background: "var(--card)", padding: 4 }} />
                </div>
              : <div style={{ width: 88, height: 88, borderRadius: "var(--r-sm)", border: "1px dashed var(--line)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--muted-2)" }}><Icon name="expenses" size={22} /></div>}
            <ImagePicker label={f.receiptImage ? t("common.edit") : t("exp.addReceipt")} icon="download" capture="environment" maxDim={1400} onPick={(d) => set("receiptImage", d)} size="sm" />
          </div>
        </div>
      </div>
    </Modal>
  );
}

function ExpensesPage() {
  useStore();
  const [lang] = useLang();
  const [q, setQ] = useState(""); const [proj, setProj] = useState("all"); const [cat, setCat] = useState("all");
  const [showForm, setShowForm] = useState(false); const [editing, setEditing] = useState(null);
  const [viewing, setViewing] = useState(null);
  const [confirm, confirmNode] = useConfirm();
  let rows = S.all("expenses").slice().sort((a, b) => (b.date || "").localeCompare(a.date || ""));
  if (proj !== "all") rows = rows.filter((r) => r.projectId === proj);
  if (cat !== "all") rows = rows.filter((r) => r.category === cat);
  if (q) rows = rows.filter((r) => (r.description + r.supplier).toLowerCase().includes(q.toLowerCase()));
  const total = rows.reduce((s, r) => s + (Number(r.amount) || 0), 0);
  const projects = S.all("projects");
  return (
    <div>
      <PageHead title={t("exp.title")} sub={lang === "en" ? "Project spending — feeds the 'Actual' column on the dashboard." : "Pengeluaran proyek — mengisi kolom 'Realisasi' di dashboard."}>
        <Button variant="primary" icon="plus" onClick={() => { setEditing(null); setShowForm(true); }}>{t("exp.new")}</Button>
      </PageHead>
      <div className="toolbar">
        <div className="search"><Icon name="search" className="ico" /><Input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("common.search")} /></div>
        <Select value={proj} onChange={(e) => setProj(e.target.value)} style={{ width: 220 }}>
          <option value="all">{t("common.all")} {t("common.project")}</option>
          {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
        </Select>
        <div className="filters"><span className={"chip" + (cat === "all" ? " on" : "")} onClick={() => setCat("all")}>{t("common.all")}</span>
          {EXP_CATEGORIES.map((c) => <span key={c} className={"chip" + (cat === c ? " on" : "")} onClick={() => setCat(c)}>{t("exp.cat." + c)}</span>)}</div>
        <div style={{ marginLeft: "auto", textAlign: "right" }}><div className="tiny muted">{t("common.total")}</div><div className="serif" style={{ fontSize: 20 }}>{S.formatRupiah(total)}</div></div>
      </div>
      <div className="card"><div className="table-wrap"><table className="tbl">
        <thead><tr><th>{t("common.date")}</th><th>{t("common.project")}</th><th>{t("common.category")}</th><th>{t("common.description")}</th><th>{t("exp.supplier")}</th><th className="num">{t("common.amount")}</th><th></th></tr></thead>
        <tbody>
          {rows.length === 0 && <tr><td colSpan="7"><Empty icon="expenses" title={t("common.empty")} /></td></tr>}
          {rows.map((r) => (
            <tr key={r.id}>
              <td data-label={t("common.date")}>{S.shortDate(r.date)}</td><td data-label={t("common.project")}>{S.projectName(r.projectId)}</td>
              <td data-label={t("common.category")}><Badge tone="neutral">{t("exp.cat." + r.category)}</Badge></td>
              <td data-label={t("common.description")} style={{ fontWeight: 500 }}>
                <div className="row" style={{ gap: 8, justifyContent: "flex-end" }}>
                  {r.receiptImage && <img src={r.receiptImage} alt="" onClick={() => setViewing(r)} title={t("exp.viewReceipt")} style={{ width: 28, height: 28, objectFit: "cover", borderRadius: 4, border: "1px solid var(--line)", cursor: "pointer", flex: "0 0 28px" }} />}
                  <span>{r.description}</span>
                </div>
              </td><td data-label={t("exp.supplier")} className="subtle">{r.supplier || "—"}</td>
              <td data-label={t("common.amount")} className="num" style={{ fontWeight: 600 }}>{S.formatRupiah(r.amount)}</td>
              <td className="num"><div className="row" style={{ gap: 2, justifyContent: "flex-end" }}>
                <Button variant="ghost" size="sm" icon="edit" onClick={() => { setEditing(r); setShowForm(true); }} />
                <Button variant="ghost" size="sm" icon="trash" onClick={() => confirm(t("common.confirmDelete"), () => S.remove("expenses", r.id))} />
              </div></td>
            </tr>
          ))}
        </tbody>
      </table></div></div>
      {showForm && <ExpenseForm expense={editing} defaultProject={proj !== "all" ? proj : null} onClose={() => setShowForm(false)} />}
      {viewing && <Modal title={t("exp.receipt") + " · " + viewing.description} onClose={() => setViewing(null)}>
        <img src={viewing.receiptImage} alt="" style={{ width: "100%", borderRadius: "var(--r-sm)" }} />
      </Modal>}
      {confirmNode}
    </div>
  );
}

/* ---------------- Settings ---------------- */
/* signature drawing pad (works with mouse + touch) */
function SignaturePadModal({ onClose, onSave }) {
  const [lang] = useLang();
  const cvRef = useRef(null);
  const drawing = useRef(false);
  const last = useRef(null);
  const dirty = useRef(false);
  useEffect(() => {
    const cv = cvRef.current; const ctx = cv.getContext("2d");
    ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, cv.width, cv.height);
    ctx.strokeStyle = "#16181a"; ctx.lineWidth = 2.6; ctx.lineCap = "round"; ctx.lineJoin = "round";
  }, []);
  const pos = (e) => {
    const cv = cvRef.current; const r = cv.getBoundingClientRect();
    const cx = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
    const cy = (e.touches ? e.touches[0].clientY : e.clientY) - r.top;
    return { x: cx * (cv.width / r.width), y: cy * (cv.height / r.height) };
  };
  const start = (e) => { e.preventDefault(); drawing.current = true; last.current = pos(e); };
  const move = (e) => {
    if (!drawing.current) return; e.preventDefault();
    const ctx = cvRef.current.getContext("2d"); const p = pos(e);
    ctx.beginPath(); ctx.moveTo(last.current.x, last.current.y); ctx.lineTo(p.x, p.y); ctx.stroke();
    last.current = p; dirty.current = true;
  };
  const end = () => { drawing.current = false; };
  const clear = () => { const cv = cvRef.current; const ctx = cv.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, cv.width, cv.height); dirty.current = false; };
  const save = () => { if (!dirty.current) return onClose(); onSave(cvRef.current.toDataURL("image/png")); onClose(); };
  return (
    <Modal title={t("set.draw")} size="lg" onClose={onClose}
      footer={<><Button variant="ghost" icon="close" onClick={clear}>{t("set.clear")}</Button><div style={{ flex: 1 }}></div><Button variant="ghost" onClick={onClose}>{t("common.cancel")}</Button><Button variant="primary" icon="check" onClick={save}>{t("set.useDrawing")}</Button></>}>
      <div className="tiny muted" style={{ marginBottom: 10 }}>{lang === "en" ? "Sign inside the box with your finger or mouse." : "Tanda tangani di dalam kotak pakai jari atau mouse."}</div>
      <canvas ref={cvRef} width={640} height={240}
        style={{ width: "100%", height: "auto", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", touchAction: "none", background: "#fff", cursor: "crosshair" }}
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end} />
    </Modal>
  );
}

/* image field with upload + (optional) draw, used for signature / stamp / header */
function SignImageField({ label, value, onChange, allowDraw, hint, bg }) {
  const [draw, setDraw] = useState(false);
  return (
    <div className="field">
      <label>{label}</label>
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start", flexWrap: "wrap" }}>
        <div style={{ width: 150, height: 84, border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: bg || "var(--paper-2)", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden", flex: "0 0 auto" }}>
          {value ? <img src={value} alt="" style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }} /> : <span className="tiny muted">—</span>}
        </div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          <ImagePicker label={t("set.upload")} icon="download" maxDim={900} accept="image/png,image/jpeg" onPick={onChange} size="sm" />
          {allowDraw && <Button size="sm" icon="edit" onClick={() => setDraw(true)}>{t("set.draw")}</Button>}
          {value && <Button size="sm" variant="ghost" icon="trash" onClick={() => onChange("")}>{t("set.clear")}</Button>}
        </div>
      </div>
      {hint && <div className="tiny muted" style={{ marginTop: 8 }}>{hint}</div>}
      {draw && <SignaturePadModal onClose={() => setDraw(false)} onSave={onChange} />}
    </div>
  );
}

function SettingsPage() {
  useStore();
  const [lang] = useLang();
  const [c, setC] = useState(S.getDB().company || {});
  const [saved, setSaved] = useState(false);
  const [confirm, confirmNode] = useConfirm();
  const set = (k, v) => { setC((o) => ({ ...o, [k]: v })); setSaved(false); };
  const save = () => { const db = S.getDB(); db.company = c; S.saveDB(db); setSaved(true); setTimeout(() => setSaved(false), 2000); };
  return (
    <div>
      <PageHead title={t("set.title")} sub={lang === "en" ? "Used on every document's letterhead and footer." : "Dipakai di kop dan footer semua dokumen."}>
        <Button variant="primary" icon="check" onClick={save}>{saved ? "✓ " + t("common.save") : t("common.save")}</Button>
      </PageHead>

      <div className="grid-2" style={{ alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <div className="card pad">
            <h2 className="section">{t("set.title")}</h2>
            <div className="form-grid">
              <Field label={t("set.companyName")} full><Input value={c.name || ""} onChange={(e) => set("name", e.target.value)} /></Field>
              <Field label={t("set.legalName")} full><Input value={c.legalName || ""} onChange={(e) => set("legalName", e.target.value)} /></Field>
              <Field label={t("set.ownerName")} full><Input value={c.ownerName || ""} onChange={(e) => set("ownerName", e.target.value)} /></Field>
              <Field label={t("set.tagline")} full><Input value={c.tagline || ""} onChange={(e) => set("tagline", e.target.value)} /></Field>
              <Field label={t("client.address")}><Input value={c.address || ""} onChange={(e) => set("address", e.target.value)} /></Field>
              <Field label="Kota / City"><Input value={c.city || ""} onChange={(e) => set("city", e.target.value)} /></Field>
              <Field label={t("client.phone")}><Input value={c.phone || ""} onChange={(e) => set("phone", e.target.value)} /></Field>
              <Field label={t("client.email")}><Input value={c.email || ""} onChange={(e) => set("email", e.target.value)} /></Field>
              <Field label="Website"><Input value={c.website || ""} onChange={(e) => set("website", e.target.value)} /></Field>
              <Field label={t("client.npwp")}><Input value={c.npwp || ""} onChange={(e) => set("npwp", e.target.value)} /></Field>
            </div>
          </div>

          <div className="card pad">
            <h2 className="section">{t("set.bank")}</h2>
            <div className="form-grid">
              <Field label={t("set.bankName")}><Input value={c.bankName || ""} onChange={(e) => set("bankName", e.target.value)} /></Field>
              <Field label={t("set.bankAccount")}><Input value={c.bankAccount || ""} onChange={(e) => set("bankAccount", e.target.value)} /></Field>
              <Field label={t("set.bankHolder")} full><Input value={c.bankHolder || ""} onChange={(e) => set("bankHolder", e.target.value)} /></Field>
              <Field label={t("set.defaultPpn")}><Input className="num" value={c.defaultPpn != null ? c.defaultPpn : 11} onChange={(e) => set("defaultPpn", parseFloat(e.target.value) || 0)} /></Field>
            </div>
          </div>

          <div className="card pad">
            <h2 className="section">{t("doc.paymentTerms")}</h2>
            <Field label={t("set.paymentTermsId")}><Textarea value={c.paymentTermsId || ""} onChange={(e) => set("paymentTermsId", e.target.value)} /></Field>
            <Field label={t("set.paymentTermsEn")}><Textarea value={c.paymentTermsEn || ""} onChange={(e) => set("paymentTermsEn", e.target.value)} /></Field>
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <div className="card pad">
            <h2 className="section">Logo</h2>
            <div style={{ display: "flex", justifyContent: "center", padding: 20, background: "var(--paper-2)", borderRadius: "var(--r)", border: "1px solid var(--line)" }}>
              <img src="assets/kay-logo.png" alt="Kay" style={{ width: 130, height: 130, objectFit: "contain" }} />
            </div>
            <div className="tiny muted" style={{ marginTop: 12, textAlign: "center" }}>{lang === "en" ? "Logo upload connects to Supabase Storage later." : "Upload logo akan terhubung ke Supabase Storage nanti."}</div>
          </div>

          <div className="card pad">
            <h2 className="section">{t("set.sign")}</h2>
            <SignImageField label={t("set.signImg")} value={c.signature || ""} onChange={(d) => set("signature", d)} allowDraw bg="#fff" hint={t("set.signHint")} />
            <SignImageField label={t("set.stampImg")} value={c.stamp || ""} onChange={(d) => set("stamp", d)} bg="#fff" />
            <SignImageField label={t("set.brandImg")} value={c.headerImage || ""} onChange={(d) => set("headerImage", d)} />
          </div>

          <div className="card pad">
            <h2 className="section">{lang === "en" ? "Letterhead Preview" : "Pratinjau Kop"}</h2>
            <div style={{ border: "1px solid var(--line)", borderRadius: "var(--r)", padding: 18, display: "flex", gap: 14, alignItems: "center" }}>
              <img src="assets/kay-logo.png" style={{ width: 54, height: 54, objectFit: "contain" }} />
              <div>
                <div className="serif" style={{ fontSize: 18, letterSpacing: "0.12em" }}>{c.name}</div>
                <div className="tiny muted">{c.legalName}</div>
                <div className="tiny muted">{c.address}, {c.city}</div>
                <div className="tiny muted">{c.phone} · {c.email}</div>
              </div>
            </div>
          </div>

          <div className="card pad" style={{ borderColor: "color-mix(in oklch, var(--neg) 30%, var(--line))" }}>
            <h2 className="section" style={{ color: "var(--neg)" }}>{t("set.danger")}</h2>
            <p className="tiny muted" style={{ marginTop: 0 }}>{t("set.resetWarn")}</p>
            <div className="row" style={{ gap: 10 }}>
              <Button icon="copy" onClick={() => confirm(t("set.resetWarn"), () => { S.reset(); S.seed(); setC(S.getDB().company); })}>{t("set.reseed")}</Button>
              <Button variant="danger" icon="trash" onClick={() => confirm(t("set.resetWarn"), () => { S.reset(); const db = S.getDB(); db.meta.seeded = true; S.saveDB(db); setC({}); })}>{t("set.clearAll")}</Button>
            </div>
          </div>
        </div>
      </div>
      {confirmNode}
    </div>
  );
}

Object.assign(window, { ExpensesPage, SettingsPage, ExpenseForm, EXP_CATEGORIES });
