/* global React, I, UI, SSSAccounting */
const { useState: useStateL, useMemo: useMemoL } = React;

// ============================================================
//  บัญชีแยกประเภท (General Ledger)
// ============================================================
function GeneralLedger() {
  const { Card, Btn, fmt0 } = window.UI;
  const A = window.SSSAccounting;
  const [selected, setSelected] = useStateL("1130");
  const [groupFilter, setGroupFilter] = useStateL("ALL");

  // Build per-account postings
  const postings = useMemoL(() => {
    const map = {};
    A.JournalEntries.forEach(e => {
      e.lines.forEach(l => {
        if (!map[l.acc]) map[l.acc] = [];
        map[l.acc].push({
          date: e.date, jv: e.id, type: e.type, ref: e.ref, desc: e.desc,
          dr: l.dr, cr: l.cr, note: l.note
        });
      });
    });
    return map;
  }, []);

  const types = ["ALL", "สินทรัพย์", "หนี้สิน", "ส่วนของเจ้าของ", "รายได้", "ค่าใช้จ่าย"];
  const visibleAccounts = A.ChartOfAccounts.filter(a => groupFilter === "ALL" || a.type === groupFilter);
  const acc = A.accByCode[selected];
  const lines = postings[selected] || [];

  // running balance
  let bal = acc?.balance || 0;
  // assume listed balance is END balance — work backward for opening
  const totDr = lines.reduce((s, l) => s + l.dr, 0);
  const totCr = lines.reduce((s, l) => s + l.cr, 0);
  const opening = acc?.normal === "Dr" ? bal - totDr + totCr : bal - totCr + totDr;

  return (
    <div className="grid" style={{gridTemplateColumns: "320px 1fr", gap: 14}}>
      {/* Left: account picker */}
      <div>
        <Card title="เลือกบัญชี" flush>
          <div style={{padding: "8px 10px", borderBottom: "1px solid var(--line-soft)", display: "flex", gap: 4, flexWrap: "wrap"}}>
            {types.map(t => (
              <button key={t} onClick={() => setGroupFilter(t)} style={{
                fontSize: 11, padding: "4px 8px", borderRadius: 12, cursor: "pointer",
                background: groupFilter === t ? "var(--ink-1)" : "transparent",
                color: groupFilter === t ? "var(--accent-ink)" : "var(--ink-2)",
                border: `1px solid ${groupFilter === t ? "var(--ink-1)" : "var(--line)"}`,
                fontFamily: "var(--font)"
              }}>{t === "ALL" ? "ทั้งหมด" : t}</button>
            ))}
          </div>
          <div style={{maxHeight: 560, overflowY: "auto"}}>
            {visibleAccounts.map(a => {
              const has = postings[a.code]?.length || 0;
              const active = selected === a.code;
              return (
                <div key={a.code} onClick={() => setSelected(a.code)} style={{
                  padding: "9px 14px",
                  borderBottom: "1px solid var(--line-soft)",
                  cursor: "pointer",
                  background: active ? "var(--surface-2)" : "transparent",
                  borderLeft: `3px solid ${active ? "var(--ink-1)" : "transparent"}`,
                  display: "flex", gap: 10, alignItems: "center"
                }}>
                  <span className="mono" style={{fontSize: 11.5, color: "var(--ink-3)", minWidth: 36}}>{a.code}</span>
                  <span style={{flex: 1, fontSize: 12.5, color: "var(--ink-1)"}}>{a.name}</span>
                  {has > 0 && <span style={{
                    fontSize: 10, padding: "1px 6px", borderRadius: 8,
                    background: "var(--surface-3)", color: "var(--ink-3)"
                  }}>{has}</span>}
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      {/* Right: detail */}
      <div style={{display: "flex", flexDirection: "column", gap: 14}}>
        {acc ? (
          <>
            <Card>
              <div style={{display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 14}}>
                <div>
                  <div style={{fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 4}}>
                    บัญชีแยกประเภท
                  </div>
                  <div style={{display: "flex", gap: 12, alignItems: "baseline"}}>
                    <span className="mono" style={{fontSize: 16, color: "var(--ink-3)"}}>{acc.code}</span>
                    <h3 style={{margin: 0, fontSize: 19, letterSpacing: "-0.01em"}}>{acc.name}</h3>
                  </div>
                  <div style={{display: "flex", gap: 10, fontSize: 12, marginTop: 8, color: "var(--ink-3)"}}>
                    <span>หมวด: <b style={{color: "var(--ink-2)"}}>{acc.type}</b></span>
                    <span>·</span>
                    <span>กลุ่ม: <b style={{color: "var(--ink-2)"}}>{acc.group}</b></span>
                    <span>·</span>
                    <span>ดุลปกติ: <b style={{color: "var(--ink-2)"}}>{acc.normal === "Dr" ? "เดบิต" : "เครดิต"}</b></span>
                  </div>
                </div>
                <div style={{textAlign: "right"}}>
                  <div style={{fontSize: 11, color: "var(--ink-3)"}}>ยอดคงเหลือ</div>
                  <div className="amount big" style={{fontSize: 24, fontWeight: 600}}>฿{fmt0(acc.balance)}</div>
                </div>
              </div>
            </Card>

            <Card title={`รายการเคลื่อนไหว · ${lines.length} รายการในงวด`} flush
              right={<Btn size="sm" kind="ghost" icon={I.download}>พิมพ์</Btn>}>
              <div className="table-wrap">
                <table className="t">
                  <thead>
                    <tr>
                      <th style={{width: 80}}>วันที่</th>
                      <th style={{width: 100}}>JV</th>
                      <th>คำอธิบาย</th>
                      <th className="right" style={{width: 110}}>เดบิต</th>
                      <th className="right" style={{width: 110}}>เครดิต</th>
                      <th className="right" style={{width: 130}}>คงเหลือ</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr style={{background: "var(--surface-2)"}}>
                      <td colSpan="3" style={{fontStyle: "italic", color: "var(--ink-3)"}}>ยอดยกมา (1 พ.ค. 2569)</td>
                      <td></td><td></td>
                      <td className="right amount">฿{fmt0(opening)} {acc.normal}</td>
                    </tr>
                    {lines.map((l, i) => {
                      // running balance
                      const prev = i === 0 ? opening : null;
                      let running = opening;
                      for (let j = 0; j <= i; j++) {
                        running += acc.normal === "Dr" ? (lines[j].dr - lines[j].cr) : (lines[j].cr - lines[j].dr);
                      }
                      return (
                        <tr key={i}>
                          <td style={{fontSize: 12}}>{l.date}</td>
                          <td className="mono" style={{fontSize: 11.5}}>
                            {l.jv}
                            <div style={{marginTop: 2}}>
                              <span style={{fontSize: 9.5, padding: "1px 5px", borderRadius: 3,
                                background: "var(--surface-3)", color: "var(--ink-3)"}}>
                                {window.JOURNAL_TYPES?.[l.type]?.short || l.type}
                              </span>
                            </div>
                          </td>
                          <td>
                            <div style={{fontSize: 12.5}}>{l.note}</div>
                            <div style={{fontSize: 11, color: "var(--ink-3)", marginTop: 1}}>{l.desc}</div>
                          </td>
                          <td className="right amount">{l.dr > 0 ? fmt0(l.dr) : ""}</td>
                          <td className="right amount">{l.cr > 0 ? fmt0(l.cr) : ""}</td>
                          <td className="right amount">฿{fmt0(running)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                  <tfoot>
                    <tr style={{borderTop: "2px solid var(--ink-1)", fontWeight: 600, background: "var(--surface-2)"}}>
                      <td colSpan="3" style={{padding: "10px 14px"}}>รวมเคลื่อนไหว</td>
                      <td className="right amount" style={{padding: "10px 14px"}}>฿{fmt0(totDr)}</td>
                      <td className="right amount" style={{padding: "10px 14px"}}>฿{fmt0(totCr)}</td>
                      <td className="right amount" style={{padding: "10px 14px"}}>฿{fmt0(acc.balance)}</td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </Card>
          </>
        ) : <Card><div className="muted">เลือกบัญชีจากด้านซ้าย</div></Card>}
      </div>
    </div>
  );
}

// ============================================================
//  ผังบัญชี (Chart of Accounts)
// ============================================================
function ChartOfAccountsView() {
  const { Card, Btn, fmt0 } = window.UI;
  const A = window.SSSAccounting;
  const grouped = useMemoL(() => {
    const g = {};
    A.ChartOfAccounts.forEach(a => {
      if (!g[a.type]) g[a.type] = {};
      if (!g[a.type][a.group]) g[a.type][a.group] = [];
      g[a.type][a.group].push(a);
    });
    return g;
  }, []);

  const typeOrder = ["สินทรัพย์", "หนี้สิน", "ส่วนของเจ้าของ", "รายได้", "ค่าใช้จ่าย"];
  const typeMeta = {
    "สินทรัพย์":      { code: "1", color: "oklch(60% 0.10 230)", subtitle: "Assets" },
    "หนี้สิน":         { code: "2", color: "oklch(58% 0.18 25)",  subtitle: "Liabilities" },
    "ส่วนของเจ้าของ":  { code: "3", color: "oklch(60% 0.10 280)", subtitle: "Equity" },
    "รายได้":         { code: "4", color: "oklch(60% 0.10 150)", subtitle: "Revenue" },
    "ค่าใช้จ่าย":      { code: "5", color: "oklch(64% 0.13 70)",  subtitle: "Expenses" }
  };

  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      {/* Summary tiles */}
      <div className="grid" style={{gridTemplateColumns: "repeat(5, 1fr)", gap: 10}}>
        {typeOrder.map(t => {
          const accs = A.ChartOfAccounts.filter(a => a.type === t);
          const sum = accs.reduce((s, a) => s + (a.balance || 0), 0);
          const m = typeMeta[t];
          return (
            <div key={t} style={{
              padding: 14, background: "var(--surface)",
              border: "1px solid var(--line)",
              borderRadius: "var(--radius)",
              borderTop: `3px solid ${m.color}`
            }}>
              <div style={{display: "flex", alignItems: "center", gap: 8}}>
                <div className="mono" style={{
                  width: 28, height: 28, borderRadius: 6, display: "grid", placeItems: "center",
                  background: m.color, color: "var(--accent-ink)", fontSize: 13, fontWeight: 600
                }}>{m.code}</div>
                <div>
                  <div style={{fontSize: 13, fontWeight: 600}}>{t}</div>
                  <div style={{fontSize: 10.5, color: "var(--ink-3)"}}>{m.subtitle}</div>
                </div>
              </div>
              <div className="amount" style={{marginTop: 10, fontSize: 17, fontWeight: 600}}>฿{fmt0(Math.abs(sum))}</div>
              <div style={{fontSize: 11, color: "var(--ink-3)", marginTop: 2}}>{accs.length} บัญชี</div>
            </div>
          );
        })}
      </div>

      {/* Detail per type */}
      {typeOrder.map(t => (
        <Card key={t} title={`${typeMeta[t].code}xxxx · ${t}`} sub={typeMeta[t].subtitle} flush>
          {Object.entries(grouped[t] || {}).map(([groupName, accs]) => (
            <div key={groupName}>
              <div style={{
                padding: "8px 16px",
                background: "var(--surface-2)",
                fontSize: 11.5, fontWeight: 600, color: "var(--ink-2)",
                textTransform: "uppercase", letterSpacing: "0.04em",
                borderBottom: "1px solid var(--line)"
              }}>{groupName}</div>
              <table className="t">
                <tbody>
                  {accs.map(a => (
                    <tr key={a.code}>
                      <td className="mono" style={{width: 80, fontSize: 12.5, color: "var(--ink-3)"}}>{a.code}</td>
                      <td style={{fontSize: 13}}>{a.name}</td>
                      <td style={{width: 80, fontSize: 11, color: "var(--ink-3)"}}>ดุลปกติ: {a.normal === "Dr" ? "Dr" : "Cr"}</td>
                      <td className="right amount" style={{width: 140}}>฿{fmt0(Math.abs(a.balance))}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ))}
        </Card>
      ))}
    </div>
  );
}

window.GeneralLedger = GeneralLedger;
window.ChartOfAccountsView = ChartOfAccountsView;
