/* global React, I, UI, SSSData, SSSAccounting */
const { useState: useStateJ, useMemo: useMemoJ, useEffect: useEffectJ } = React;

// ============================================================
//  สมุดรายวัน + บัญชีแยกประเภท + ผังบัญชี
//  ตามมาตรฐานบัญชีไทย พ.ร.บ.การบัญชี พ.ศ. 2543
// ============================================================

const JOURNAL_TYPES = {
  GJ: { label: "สมุดรายวันทั่วไป", short: "ทั่วไป", color: "var(--ink-1)" },
  SJ: { label: "สมุดรายวันขาย",   short: "ขาย",   color: "oklch(60% 0.10 150)" },
  PJ: { label: "สมุดรายวันซื้อ",   short: "ซื้อ",   color: "oklch(55% 0.10 230)" },
  CR: { label: "สมุดรายวันรับเงิน", short: "รับเงิน", color: "oklch(60% 0.10 150)" },
  CP: { label: "สมุดรายวันจ่ายเงิน", short: "จ่ายเงิน", color: "oklch(58% 0.18 25)" }
};

const fmt2 = (n) => (n || 0).toLocaleString("th-TH", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

function JournalRoot({ navigate }) {
  const { Btn, Card, PageHead } = window.UI;
  const [view, setView] = useStateJ("journal"); // journal | ledger | coa | auto
  const [newOpen, setNewOpen] = useStateJ(false);

  useEffectJ(() => {
    window.openNewJournal = () => setNewOpen(true);
    return () => { if (window.openNewJournal) delete window.openNewJournal; };
  }, []);

  return (
    <>
      <PageHead
        title="สมุดรายวันและบัญชีแยกประเภท"
        sub="ตามมาตรฐานบัญชีไทย พ.ร.บ.การบัญชี พ.ศ. 2543 · งวดบัญชี 1 ม.ค. – 31 ธ.ค. 2569"
        right={<>
          <Btn icon={I.download} kind="ghost" onClick={() => window.exportAllBooksExcel && window.exportAllBooksExcel()}>ส่งออกทุกสมุด (Excel)</Btn>
          <Btn icon={I.plus} kind="primary" onClick={() => setNewOpen(true)}>บันทึกรายการใหม่</Btn>
        </>}
      />

      <SubNav view={view} setView={setView}/>

      {view === "journal" && <window.JournalHub navigate={navigate}/>}
      {view === "ledger" && <window.GeneralLedger/>}
      {view === "coa" && <window.ChartOfAccountsView/>}
      {view === "auto" && <window.AutoPosting/>}

      <window.NewJournalDrawer open={newOpen} onClose={() => setNewOpen(false)}/>
    </>
  );
}

function SubNav({ view, setView }) {
  const A = window.SSSAccounting;
  const pendingCount = window.buildPendingQueue ? window.buildPendingQueue().length : 0;
  const items = [
    { key: "journal", label: "สมุดรายวัน", icon: I.book, desc: "บันทึกรายการตามลำดับวันที่" },
    { key: "ledger", label: "บัญชีแยกประเภท", icon: I.doc, desc: "ดูเคลื่อนไหวรายบัญชี" },
    { key: "coa", label: "ผังบัญชี", icon: I.cube3d, desc: "รหัสบัญชี 4 หลัก" },
    { key: "auto", label: "Auto-posting", icon: I.sparkle, desc: "บันทึกอัตโนมัติจากเอกสาร", badge: pendingCount }
  ];
  return (
    <div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 14}}>
      {items.map(it => {
        const active = view === it.key;
        return (
          <button
            key={it.key}
            onClick={() => setView(it.key)}
            style={{
              textAlign: "left",
              padding: "12px 14px",
              background: active ? "var(--surface)" : "var(--surface-2)",
              border: `1px solid ${active ? "var(--ink-1)" : "var(--line)"}`,
              borderRadius: "var(--radius)",
              cursor: "pointer",
              display: "flex", gap: 10, alignItems: "center",
              boxShadow: active ? "var(--shadow-sm)" : "none",
              position: "relative"
            }}>
            {React.createElement(it.icon, { size: 18, stroke: active ? "var(--ink-1)" : "var(--ink-3)" })}
            <div style={{flex: 1, minWidth: 0}}>
              <div style={{fontWeight: 600, fontSize: 13.5, color: "var(--ink-1)", display: "flex", alignItems: "center", gap: 6}}>
                {it.label}
                {it.badge > 0 && (
                  <span style={{
                    fontSize: 10.5, padding: "1px 6px", borderRadius: 8,
                    background: "var(--warning)", color: "var(--accent-ink)", fontWeight: 600
                  }}>{it.badge}</span>
                )}
              </div>
              <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 2}}>{it.desc}</div>
            </div>
            {active && <I.check size={14} stroke="var(--ink-1)"/>}
          </button>
        );
      })}
    </div>
  );
}

// ============================================================
//  สมุดรายวัน — Journal Book
// ============================================================
function JournalBook({ onOpen }) {
  const { Card, Btn, Badge, fmt0 } = window.UI;
  const A = window.SSSAccounting;
  const [filter, setFilter] = useStateJ("ALL");
  const [search, setSearch] = useStateJ("");

  const filtered = useMemoJ(() => {
    return A.JournalEntries.filter(e => {
      if (filter !== "ALL" && e.type !== filter) return false;
      if (search) {
        const q = search.toLowerCase();
        if (!e.desc.toLowerCase().includes(q) && !e.ref.toLowerCase().includes(q) && !e.id.toLowerCase().includes(q)) return false;
      }
      return true;
    });
  }, [filter, search]);

  const totalDr = filtered.reduce((s, e) => s + e.lines.reduce((a, l) => a + l.dr, 0), 0);
  const totalCr = filtered.reduce((s, e) => s + e.lines.reduce((a, l) => a + l.cr, 0), 0);

  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      {/* Type filter pills */}
      <div style={{display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap"}}>
        <FilterPill active={filter === "ALL"} onClick={() => setFilter("ALL")} count={A.JournalEntries.length}>ทั้งหมด</FilterPill>
        {Object.entries(JOURNAL_TYPES).map(([k, v]) => {
          const c = A.JournalEntries.filter(e => e.type === k).length;
          return <FilterPill key={k} active={filter === k} onClick={() => setFilter(k)} count={c} color={v.color}>{v.short}</FilterPill>;
        })}
        <div style={{flex: 1}}/>
        <div className="search" style={{maxWidth: 280, position: "relative"}}>
          <I.search size={14}/>
          <input placeholder="ค้นหา JV, เอกสารอ้างอิง, คำอธิบาย…" value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
      </div>

      {/* Legal note */}
      <div style={{
        padding: "10px 14px", background: "var(--info-bg)", border: "1px solid var(--info)",
        borderRadius: "var(--radius-sm)", display: "flex", gap: 10, alignItems: "flex-start",
        fontSize: 12, color: "var(--ink-2)"
      }}>
        <I.shield size={14} stroke="var(--info)" style={{flexShrink: 0, marginTop: 2}}/>
        <div>
          <b>มาตรา 7 & 14 พ.ร.บ.การบัญชี พ.ศ. 2543:</b> ต้องลงรายการในบัญชีรายวันภายใน 15 วันนับจากวันสิ้นเดือนที่รายการนั้นเกิดขึ้น
          และต้องเก็บรักษาบัญชี เอกสารประกอบการลงบัญชีไว้ไม่น้อยกว่า <b>5 ปี</b> นับแต่วันปิดบัญชี ผู้ทำบัญชีต้องเป็นผู้มีคุณสมบัติตาม
          พ.ร.บ.วิชาชีพบัญชี พ.ศ. 2547
        </div>
      </div>

      {/* Journal table */}
      <Card flush>
        <div className="table-wrap">
          <table className="t journal-t">
            <thead>
              <tr>
                <th style={{width: 88}}>วันที่</th>
                <th style={{width: 120}}>เลขที่ JV</th>
                <th style={{width: 80}}>รหัสบัญชี</th>
                <th>ชื่อบัญชี / คำอธิบาย</th>
                <th style={{width: 140}}>อ้างอิง</th>
                <th className="right" style={{width: 120}}>เดบิต (Dr.)</th>
                <th className="right" style={{width: 120}}>เครดิต (Cr.)</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(e => <JournalRow key={e.id} entry={e} onOpen={onOpen}/>)}
            </tbody>
            <tfoot>
              <tr style={{borderTop: "2px solid var(--ink-1)", background: "var(--surface-2)", fontWeight: 600}}>
                <td colSpan="5" style={{padding: "12px 14px"}}>รวม {filtered.length} รายการ · ผลรวมต้องเท่ากัน {totalDr === totalCr ? "✓" : "⚠ ไม่สมดุล"}</td>
                <td className="right amount" style={{padding: "12px 14px"}}>฿{fmt2(totalDr)}</td>
                <td className="right amount" style={{padding: "12px 14px"}}>฿{fmt2(totalCr)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </Card>
    </div>
  );
}

function FilterPill({ active, onClick, count, color, children }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: "6px 12px",
        background: active ? "var(--ink-1)" : "var(--surface)",
        color: active ? "var(--accent-ink)" : "var(--ink-2)",
        border: `1px solid ${active ? "var(--ink-1)" : "var(--line)"}`,
        borderRadius: 999,
        fontSize: 12.5,
        fontFamily: "var(--font)",
        cursor: "pointer",
        display: "inline-flex", alignItems: "center", gap: 6,
      }}>
      {color && !active && <span style={{width: 6, height: 6, borderRadius: "50%", background: color}}/>}
      {children}
      {count !== undefined && <span style={{
        opacity: 0.7, fontSize: 11,
        padding: "1px 6px", borderRadius: 8,
        background: active ? "rgba(255,255,255,0.15)" : "var(--surface-3)"
      }}>{count}</span>}
    </button>
  );
}

function JournalRow({ entry, onOpen }) {
  const A = window.SSSAccounting;
  const T = JOURNAL_TYPES[entry.type];
  return (
    <>
      {entry.lines.map((l, i) => {
        const acc = A.accByCode[l.acc];
        const first = i === 0;
        const last = i === entry.lines.length - 1;
        return (
          <tr key={i} className="jrow" onClick={() => onOpen && onOpen(entry)} style={{
            borderBottom: last ? "1px solid var(--line-strong)" : "1px solid var(--line-soft)",
            background: first ? "var(--surface)" : "var(--surface)",
            cursor: onOpen ? "pointer" : "default"
          }}>
            <td style={{verticalAlign: "top", paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4}}>
              {first && <>
                <div style={{fontWeight: 500, fontSize: 12.5}}>{entry.date}</div>
                <div style={{fontSize: 11, color: "var(--ink-3)", marginTop: 2}}>{entry.by}</div>
              </>}
            </td>
            <td style={{verticalAlign: "top", paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4}}>
              {first && <>
                <span className="mono" style={{fontSize: 12, fontWeight: 600}}>{entry.id}</span>
                <div style={{marginTop: 4}}>
                  <span style={{
                    fontSize: 10, padding: "2px 6px", borderRadius: 4,
                    background: T.color, color: "var(--accent-ink)", fontWeight: 500
                  }}>{T.short}</span>
                </div>
              </>}
            </td>
            <td className="mono" style={{
              fontSize: 12,
              paddingLeft: l.cr > 0 ? 28 : 14,
              paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4,
              color: "var(--ink-2)"
            }}>{l.acc}</td>
            <td style={{paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4, paddingLeft: l.cr > 0 ? 28 : 14}}>
              <div style={{fontSize: 13}}>{acc ? acc.name : "?"}</div>
              {first && <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 2, fontStyle: "italic"}}>— {entry.desc}</div>}
              {l.note && !first && <div style={{fontSize: 11, color: "var(--ink-4)", marginTop: 1}}>{l.note}</div>}
              {l.note && first && <div style={{fontSize: 11, color: "var(--ink-4)", marginTop: 1}}>{l.note}</div>}
            </td>
            <td style={{verticalAlign: "top", paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4}}>
              {first && <span className="mono" style={{fontSize: 11, color: "var(--ink-3)"}}>{entry.ref}</span>}
            </td>
            <td className="right amount" style={{paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4, fontVariantNumeric: "tabular-nums"}}>
              {l.dr > 0 ? fmt2(l.dr) : ""}
            </td>
            <td className="right amount" style={{paddingTop: first ? 12 : 6, paddingBottom: last ? 12 : 4, fontVariantNumeric: "tabular-nums"}}>
              {l.cr > 0 ? fmt2(l.cr) : ""}
            </td>
          </tr>
        );
      })}
    </>
  );
}

window.JournalRoot = JournalRoot;
window.JournalBook = JournalBook;
window.JOURNAL_TYPES = JOURNAL_TYPES;
