/* Kay Construction — Auto termin (payment) schedule + retention tracking. Embeds in project detail. */

function terminTemplates(lang) {
  const P = (id, en) => (lang === "en" ? en : id);
  return [
    { key: "std", label: P("DP 30 · 30 · 30 · Retensi 10", "DP 30 · 30 · 30 · Retention 10"), rows: [
      { desc: P("Uang Muka (DP) 30%", "Down Payment 30%"), percent: 30 },
      { desc: P("Progres 30%", "Progress 30%"), percent: 30 },
      { desc: P("Progres 30%", "Progress 30%"), percent: 30 },
      { desc: P("Retensi 10%", "Retention 10%"), percent: 10, retention: true, releaseDays: 90 }
    ] },
    { key: "433", label: P("DP 40 · 30 · Pelunasan 30", "DP 40 · 30 · Final 30"), rows: [
      { desc: P("Uang Muka (DP) 40%", "Down Payment 40%"), percent: 40 },
      { desc: P("Progres 30%", "Progress 30%"), percent: 30 },
      { desc: P("Pelunasan 30%", "Final Payment 30%"), percent: 30 }
    ] },
    { key: "5050", label: P("DP 50 · Pelunasan 50", "DP 50 · Final 50"), rows: [
      { desc: P("Uang Muka (DP) 50%", "Down Payment 50%"), percent: 50 },
      { desc: P("Pelunasan 50%", "Final Payment 50%"), percent: 50 }
    ] }
  ];
}

function TerminSchedule({ p }) {
  useStore();
  const [lang] = useLang();
  const [tplKey, setTplKey] = useState("std");
  const [confirm, confirmNode] = useConfirm();
  const termins = S.terminsFor(p.id);
  const totals = S.terminBilledTotals(p.id);
  const contract = S.effectiveContract(p.id);
  const templates = terminTemplates(lang);

  const generate = () => {
    const tpl = templates.find((x) => x.key === tplKey) || templates[0];
    const doIt = () => S.generateTermins(p.id, tpl.rows);
    if (termins.length) confirm(t("trm.keepBilled"), doIt); else doIt();
  };
  const issue = (tm) => {
    const inv = saveDoc("invoices", "invoice", {
      projectId: p.id, terminNo: tm.no, terminDesc: tm.desc, issueDate: S.todayISO(), dueDate: S.addDays(S.todayISO(), 7),
      flatAmount: tm.amount, discount: 0, ppnPercent: S.getDB().company.defaultPpn || 11, status: "terkirim", language: lang, note: ""
    });
    S.upsert("termins", { ...tm, invoiceId: inv.id, status: "terbit", issuedDate: S.todayISO() });
    go("#/dokumen/invoice/" + inv.id);
  };

  return (
    <div className="card">
      <div className="card-head">
        <div>
          <h2 className="section" style={{ margin: 0 }}>{t("trm.title")}</h2>
          <div className="tiny muted" style={{ marginTop: 3 }}>{t("trm.sub")} · {t("col.contract")}: <strong>{S.formatRupiah(contract)}</strong></div>
        </div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          <Select value={tplKey} onChange={(e) => setTplKey(e.target.value)} style={{ width: 230 }}>
            {templates.map((x) => <option key={x.key} value={x.key}>{x.label}</option>)}
          </Select>
          <Button icon="wand" onClick={generate}>{termins.length ? t("trm.regenerate") : t("trm.generate")}</Button>
        </div>
      </div>
      <div className="card-body" style={{ paddingTop: 8 }}>
        {termins.length === 0 ? <div className="empty" style={{ padding: 30 }}><div className="t">{t("trm.empty")}</div></div> : (
          <>
            <div className="table-wrap"><table className="tbl">
              <thead><tr><th style={{ width: 40 }}>#</th><th>{t("doc.terminDesc")}</th><th className="num">%</th><th className="num">{t("common.amount")}</th><th>{t("common.status")}</th><th></th></tr></thead>
              <tbody>
                {termins.map((tm) => (
                  <tr key={tm.id}>
                    <td data-label="#" className="mono">{tm.no}</td>
                    <td data-label={t("doc.terminDesc")} style={{ fontWeight: 500 }}>{tm.desc}{tm.retention && <span style={{ marginLeft: 8 }}><Badge tone="warn">{t("ret.title")}</Badge></span>}</td>
                    <td data-label="%" className="num subtle">{tm.percent}%</td>
                    <td data-label={t("common.amount")} className="num" style={{ fontWeight: 600 }}>{S.formatRupiah(tm.amount)}</td>
                    <td data-label={t("common.status")}>{tm.invoiceId ? <Badge tone="info">{t("trm.issued")}</Badge> : <Badge tone="neutral">{t("trm.planned")}</Badge>}</td>
                    <td className="num">{tm.invoiceId
                      ? <Button size="sm" variant="ghost" icon="invoice" onClick={() => go("#/dokumen/invoice/" + tm.invoiceId)}>{t("trm.viewInvoice")}</Button>
                      : <Button size="sm" icon="arrow" onClick={() => issue(tm)}>{t("trm.issue")}</Button>}</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
            <div className="row" style={{ gap: 26, marginTop: 16, flexWrap: "wrap" }}>
              <div><div className="tiny muted">{t("trm.plannedTotal")}</div><div className="serif" style={{ fontSize: 18 }}>{S.formatRupiah(totals.planned)}</div></div>
              <div><div className="tiny muted">{t("trm.billed")}</div><div className="serif" style={{ fontSize: 18, color: "var(--pos)" }}>{S.formatRupiah(totals.billed)}</div></div>
              <div><div className="tiny muted">{t("trm.unbilled")}</div><div className="serif" style={{ fontSize: 18 }}>{S.formatRupiah(totals.unbilled)}</div></div>
            </div>
          </>
        )}
      </div>
      {confirmNode}
    </div>
  );
}

/* retention list — reusable on reports + dashboard (compact) */
function RetentionList({ compact }) {
  useStore();
  const [lang] = useLang();
  const items = S.retentionItems();
  const markCashed = (tm) => S.upsert("termins", { ...tm, released: true, releaseDate: tm.releaseDate || S.todayISO() });
  if (items.length === 0) return <div className="muted tiny" style={{ padding: "10px 0" }}>{t("ret.empty")}</div>;
  return (
    <div className="table-wrap"><table className="tbl">
      <thead><tr><th>{t("common.project")}</th><th className="num">{t("ret.held")}</th><th>{t("ret.release")}</th><th>{t("common.status")}</th>{!compact && <th></th>}</tr></thead>
      <tbody>
        {items.map((r) => {
          const due = !r.cashed && r.dueDays <= 0;
          return (
            <tr key={r.termin.id} className="clickable" onClick={() => go("#/proyek/" + r.project.id)}>
              <td data-label={t("common.project")}><div style={{ fontWeight: 500 }}>{r.project.name}</div><div className="subtle mono">{r.project.code}</div></td>
              <td data-label={t("ret.held")} className="num" style={{ fontWeight: 600 }}>{S.formatRupiah(r.amount)}</td>
              <td data-label={t("ret.release")}><div>{S.shortDate(r.releaseDate)}</div>{!r.cashed && <div className="tiny" style={{ color: due ? "var(--pos)" : "var(--muted)" }}>{due ? t("ret.reminder") : (t("dash.dueIn") + " " + r.dueDays + " " + t("dash.days"))}</div>}</td>
              <td data-label={t("common.status")}>{r.cashed ? <Badge tone="pos">{t("ret.cashed")}</Badge> : <Badge tone="warn">{t("ret.pending")}</Badge>}</td>
              {!compact && <td className="num" onClick={(e) => e.stopPropagation()}>{!r.cashed && <Button size="sm" icon="check" onClick={() => markCashed(r.termin)}>{t("ret.markCashed")}</Button>}</td>}
            </tr>
          );
        })}
      </tbody>
    </table></div>
  );
}

Object.assign(window, { TerminSchedule, RetentionList, terminTemplates });
