/* global React, I, UI, SSSData, SSSAccounting, XLSX */
const { useState: useStateD2, useMemo: useMemoD2 } = React;

// ============================================================
//  รายละเอียดการบันทึกบัญชี (Journal Entry Detail)
//  แสดง JV เต็ม + ลิงก์เอกสารต้นฉบับ + รูปสแกนเอกสาร
// ============================================================
function JournalEntryDetail({ entry, navigate, onClose }) {
  const { Drawer, Btn, Badge } = window.UI;
  const A = window.SSSAccounting;
  const T = window.JOURNAL_TYPES[entry.type];
  const spec = window.BOOK_SPECS[entry.type];

  const totDr = entry.lines.reduce((s, l) => s + l.dr, 0);
  const totCr = entry.lines.reduce((s, l) => s + l.cr, 0);
  const refs = entry.ref.split("/").map(r => window.resolveRef(r));

  return (
    <Drawer open={true} onClose={onClose} wide
      title={<span style={{display: "flex", alignItems: "center", gap: 10}}>
        <span style={{fontSize: 10.5, padding: "2px 8px", borderRadius: 4, background: T.color, color: "var(--accent-ink)", fontWeight: 500}}>{T.short}</span>
        รายการบันทึกบัญชี <span className="mono" style={{color: "var(--ink-3)"}}>{entry.id}</span>
      </span>}
      footer={<>
        <div style={{flex: 1, fontSize: 12, color: totDr === totCr ? "var(--success)" : "var(--warning)"}}>
          {totDr === totCr ? <><I.check size={12}/> รายการสมดุล (Dr = Cr)</> : "⚠ ไม่สมดุล"}
        </div>
        <Btn kind="ghost" icon={I.download} onClick={() => exportEntryExcel(entry)}>ส่งออก Excel</Btn>
        <Btn kind="ghost" onClick={onClose}>ปิด</Btn>
      </>}>

      {/* Meta grid */}
      <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 18px", marginBottom: 16,
        padding: "12px 14px", background: "var(--surface-2)", borderRadius: "var(--radius-sm)"}}>
        <MetaRow label="สมุดรายวัน" value={spec.title}/>
        <MetaRow label="วันที่ลงรายการ" value={entry.date}/>
        <MetaRow label="ผู้บันทึก" value={entry.by}/>
        <MetaRow label="เลขที่อ้างอิง" value={entry.ref} mono/>
      </div>
      <div style={{fontSize: 13, color: "var(--ink-2)", marginBottom: 16, lineHeight: 1.5}}>
        <span style={{fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em"}}>คำอธิบายรายการ</span>
        <div style={{marginTop: 3}}>{entry.desc}</div>
      </div>

      {/* JV table */}
      <SectionLabel icon={I.book}>การบันทึกบัญชี (บัญชีคู่)</SectionLabel>
      <div style={{border: "1px solid var(--line)", borderRadius: "var(--radius-sm)", overflow: "hidden", marginBottom: 18}}>
        <table style={{width: "100%", borderCollapse: "collapse", fontSize: 12.5}}>
          <thead>
            <tr style={{background: "var(--surface-2)"}}>
              <th style={detTh}>รหัส</th>
              <th style={detTh}>ชื่อบัญชี</th>
              <th style={{...detTh, textAlign: "right", width: 120}}>เดบิต</th>
              <th style={{...detTh, textAlign: "right", width: 120}}>เครดิต</th>
            </tr>
          </thead>
          <tbody>
            {entry.lines.map((l, i) => {
              const acc = A.accByCode[l.acc];
              return (
                <tr key={i} style={{borderTop: "1px solid var(--line-soft)"}}>
                  <td style={{...detTd, paddingLeft: l.cr > 0 ? 34 : 14, fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--ink-3)", verticalAlign: "top"}}>{l.acc}</td>
                  <td style={{...detTd, paddingLeft: l.cr > 0 ? 22 : 0}}>
                    <div>{acc?.name || "?"}</div>
                    {l.note && <div style={{fontSize: 11, color: "var(--ink-4)", marginTop: 1}}>{l.note}</div>}
                  </td>
                  <td style={{...detTd, textAlign: "right", fontVariantNumeric: "tabular-nums"}}>{l.dr > 0 ? fmtEntry(l.dr) : ""}</td>
                  <td style={{...detTd, textAlign: "right", fontVariantNumeric: "tabular-nums"}}>{l.cr > 0 ? fmtEntry(l.cr) : ""}</td>
                </tr>
              );
            })}
          </tbody>
          <tfoot>
            <tr style={{borderTop: "2px solid var(--ink-1)", background: "var(--surface-2)", fontWeight: 600}}>
              <td colSpan="2" style={detTd}>รวม</td>
              <td style={{...detTd, textAlign: "right", fontVariantNumeric: "tabular-nums"}}>{fmtEntry(totDr)}</td>
              <td style={{...detTd, textAlign: "right", fontVariantNumeric: "tabular-nums"}}>{fmtEntry(totCr)}</td>
            </tr>
          </tfoot>
        </table>
      </div>

      {/* Source documents */}
      <SectionLabel icon={I.paperclip}>เอกสารต้นฉบับในระบบ</SectionLabel>
      <div style={{display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 18}}>
        {refs.map((r, i) => (
          <button key={i}
            onClick={() => r.route && navigate(`${r.route}/${r.token}`)}
            disabled={!r.route}
            style={{
              display: "flex", alignItems: "center", gap: 8, padding: "8px 12px",
              background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius-sm)",
              cursor: r.route ? "pointer" : "default", fontFamily: "var(--font)", textAlign: "left",
              opacity: r.route ? 1 : 0.7
            }}>
            <div style={{width: 30, height: 30, borderRadius: 5, background: "var(--surface-2)",
              display: "grid", placeItems: "center", color: "var(--ink-3)", flexShrink: 0}}>
              <I.doc size={15}/>
            </div>
            <div>
              <div style={{fontSize: 11, color: "var(--ink-3)"}}>{r.label}</div>
              <div className="mono" style={{fontSize: 12, fontWeight: 600, color: "var(--ink-1)"}}>{r.token}</div>
            </div>
            {r.route && <I.chevronRight size={13} stroke="var(--ink-3)"/>}
          </button>
        ))}
      </div>

      {/* Scanned image attachments */}
      <SectionLabel icon={I.upload}>รูปสแกนเอกสาร / ไฟล์แนบ</SectionLabel>
      <JVScanPanel entry={entry}/>
    </Drawer>
  );
}

function MetaRow({ label, value, mono }) {
  return (
    <div>
      <div style={{fontSize: 10.5, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em"}}>{label}</div>
      <div className={mono ? "mono" : ""} style={{fontSize: 12.5, color: "var(--ink-1)", marginTop: 2}}>{value}</div>
    </div>
  );
}

function SectionLabel({ icon, children }) {
  return (
    <div style={{display: "flex", alignItems: "center", gap: 7, marginBottom: 10, fontSize: 11.5,
      fontWeight: 600, color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.04em"}}>
      {icon && React.createElement(icon, { size: 13, stroke: "var(--ink-3)" })}
      {children}
    </div>
  );
}

const detTh = { padding: "8px 14px", textAlign: "left", fontWeight: 500, color: "var(--ink-3)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.04em" };
const detTd = { padding: "9px 14px" };
const fmtEntry = (n) => (n || 0).toLocaleString("th-TH", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// ============================================================
//  Scan / attachment panel — persists per JV in localStorage
// ============================================================
function JVScanPanel({ entry }) {
  const key = `sss-jvdoc-${entry.id}`;
  const [files, setFiles] = useStateD2(() => {
    try {
      const saved = JSON.parse(localStorage.getItem(key) || "null");
      if (saved) return saved;
    } catch {}
    return seedScans(entry);
  });
  const [preview, setPreview] = useStateD2(null);

  const persist = (list) => {
    setFiles(list);
    try { localStorage.setItem(key, JSON.stringify(list)); } catch {}
  };

  const onPick = (e) => {
    const picked = [...e.target.files];
    Promise.all(picked.map(f => new Promise(res => {
      const reader = new FileReader();
      reader.onload = () => res({
        name: f.name, url: reader.result, size: f.size, type: f.type,
        uploadedAt: new Date().toLocaleString("th-TH", { day: "2-digit", month: "short", year: "2-digit", hour: "2-digit", minute: "2-digit" })
      });
      reader.readAsDataURL(f);
    }))).then(loaded => {
      persist([...files, ...loaded]);
      window.toast && window.toast(`แนบเอกสาร ${loaded.length} ไฟล์`);
    });
    e.target.value = "";
  };

  const remove = (i) => persist(files.filter((_, j) => j !== i));

  return (
    <>
      <div style={{display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))", gap: 10, marginBottom: 10}}>
        {files.map((f, i) => {
          const isImg = (f.type || "").startsWith("image/") || (f.url || "").startsWith("data:image");
          return (
            <div key={i} style={{border: "1px solid var(--line)", borderRadius: "var(--radius-sm)", overflow: "hidden", background: "var(--surface)"}}>
              <div onClick={() => isImg ? setPreview(f) : window.open(f.url, "_blank")}
                style={{height: 130, cursor: "pointer", background: "var(--surface-2)", display: "grid", placeItems: "center", position: "relative"}}>
                {isImg
                  ? <img src={f.url} alt={f.name} style={{width: "100%", height: "100%", objectFit: "cover"}}/>
                  : <div style={{color: "var(--ink-3)", fontWeight: 600, fontSize: 12}}>PDF</div>}
                {f.seed && <span style={{position: "absolute", top: 6, left: 6, fontSize: 9.5, padding: "2px 6px", borderRadius: 3, background: "rgba(0,0,0,0.55)", color: "#fff"}}>ตัวอย่างนำเข้า</span>}
              </div>
              <div style={{padding: "7px 9px", display: "flex", alignItems: "center", gap: 6}}>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontSize: 11, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{f.name}</div>
                  <div style={{fontSize: 10, color: "var(--ink-3)"}}>{f.uploadedAt || "นำเข้าแล้ว"}</div>
                </div>
                <button onClick={() => remove(i)} className="icon-btn" style={{padding: 3}} title="ลบ"><I.trash size={11}/></button>
              </div>
            </div>
          );
        })}
        <label style={{cursor: "pointer", border: "1.5px dashed var(--line-strong)", borderRadius: "var(--radius-sm)",
          display: "grid", placeItems: "center", minHeight: 130, color: "var(--ink-3)", textAlign: "center", padding: 10}}>
          <input type="file" accept="image/*,application/pdf" multiple style={{display: "none"}} onChange={onPick}/>
          <div>
            <I.upload size={20}/>
            <div style={{fontSize: 11.5, marginTop: 6}}>แนบรูป/สแกน</div>
            <div style={{fontSize: 10, marginTop: 2}}>JPG, PNG, PDF</div>
          </div>
        </label>
      </div>
      <div style={{fontSize: 11, color: "var(--ink-4)"}}>
        <I.shield size={11} style={{verticalAlign: "-1px"}}/> ตาม พ.ร.บ.การบัญชี ม.14 — เก็บเอกสารประกอบการลงบัญชีไม่น้อยกว่า 5 ปี
      </div>

      {preview && (
        <div className="scrim" style={{display: "flex", alignItems: "center", justifyContent: "center", padding: 24, zIndex: 200}} onClick={() => setPreview(null)}>
          <div style={{position: "relative", maxWidth: "92vw", maxHeight: "90vh"}} onClick={e => e.stopPropagation()}>
            <button className="icon-btn" onClick={() => setPreview(null)} style={{position: "absolute", top: -36, right: 0, background: "#fff"}}><I.close size={14}/></button>
            <img src={preview.url} alt={preview.name} style={{maxWidth: "92vw", maxHeight: "86vh", borderRadius: 6, boxShadow: "0 20px 60px rgba(0,0,0,0.4)"}}/>
            <div style={{position: "absolute", left: 0, bottom: -28, color: "#fff", fontSize: 12}}>{preview.name}</div>
          </div>
        </div>
      )}
    </>
  );
}

// สร้างภาพเอกสารตัวอย่าง (SVG) สำหรับรายการที่มีใบกำกับ เพื่อสาธิตการลิงก์รูปเอกสาร
function seedScans(entry) {
  const refs = entry.ref.split("/").map(r => window.resolveRef(r));
  const primary = refs.find(r => ["TX", "TI-V", "INV", "RC", "PV"].includes(r.p));
  if (!primary) return [];
  const party = window.extractParty(entry);
  const total = entry.lines.reduce((s, l) => s + l.dr, 0);
  const svg = docSVG(primary.label, primary.token, entry.date, party, total);
  return [{
    name: `${primary.token}.svg`,
    url: "data:image/svg+xml;utf8," + encodeURIComponent(svg),
    type: "image/svg+xml",
    seed: true
  }];
}

function docSVG(docLabel, docNo, date, party, total) {
  const baht = (total || 0).toLocaleString("th-TH", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return `<svg xmlns="http://www.w3.org/2000/svg" width="595" height="780" viewBox="0 0 595 780" font-family="sans-serif">
<rect width="595" height="780" fill="#fdfdfb"/>
<rect x="28" y="28" width="539" height="724" fill="#ffffff" stroke="#e2e0db"/>
<rect x="28" y="28" width="539" height="78" fill="#1c1c1a"/>
<text x="52" y="64" fill="#fff" font-size="22" font-weight="700">SSS</text>
<text x="52" y="88" fill="#bdbdb8" font-size="12">Triple S Creative · บริษัท ทริปเปิ้ลเอส ครีเอทีฟ จำกัด</text>
<text x="543" y="60" fill="#fff" font-size="15" font-weight="700" text-anchor="end">${escapeXml(docLabel)}</text>
<text x="543" y="84" fill="#dcdcd8" font-size="13" text-anchor="end">${escapeXml(docNo)}</text>
<text x="52" y="150" fill="#6b6b66" font-size="12">วันที่</text>
<text x="52" y="170" fill="#1c1c1a" font-size="14">${escapeXml(date)}</text>
<text x="300" y="150" fill="#6b6b66" font-size="12">คู่ค้า</text>
<text x="300" y="170" fill="#1c1c1a" font-size="14">${escapeXml(party || "-")}</text>
<line x1="52" y1="200" x2="543" y2="200" stroke="#e2e0db"/>
<rect x="52" y="220" width="491" height="34" fill="#f4f3f0"/>
<text x="64" y="242" fill="#6b6b66" font-size="12">รายการ</text>
<text x="531" y="242" fill="#6b6b66" font-size="12" text-anchor="end">จำนวนเงิน</text>
<text x="64" y="286" fill="#2c2c2a" font-size="13">รายการสินค้า/บริการตามเอกสาร</text>
<text x="531" y="286" fill="#2c2c2a" font-size="13" text-anchor="end">${baht}</text>
<line x1="52" y1="320" x2="543" y2="320" stroke="#eeece8"/>
<text x="64" y="352" fill="#6b6b66" font-size="13">ภาษีมูลค่าเพิ่ม 7% / ยอดสุทธิ</text>
<line x1="52" y1="380" x2="543" y2="380" stroke="#1c1c1a"/>
<text x="64" y="410" fill="#1c1c1a" font-size="15" font-weight="700">ยอดรวมทั้งสิ้น (บาท)</text>
<text x="531" y="410" fill="#1c1c1a" font-size="17" font-weight="700" text-anchor="end">${baht}</text>
<rect x="380" y="640" width="163" height="1" fill="#9a9a95"/>
<text x="461" y="662" fill="#6b6b66" font-size="11" text-anchor="middle">ผู้มีอำนาจลงนาม</text>
<text x="52" y="720" fill="#b8b8b3" font-size="10">เอกสารตัวอย่างที่นำเข้าระบบ — เชื่อมโยงกับการบันทึกบัญชี</text>
</svg>`;
}

function escapeXml(s) {
  return String(s || "").replace(/[<>&'"]/g, c => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&apos;", '"': "&quot;" }[c]));
}

window.JournalEntryDetail = JournalEntryDetail;
