// System Architecture: data model + workflow diagrams + sample-data tables

function ArchitecturePage({ lang }) {
  const [tab, setTab] = useState("data");
  return (
    <div className="anim-fadein">
      <PageHeader
        title={lang === "th" ? "ภาพรวมระบบ" : "System Architecture"}
        subtitle={lang === "th" ? "Data model หลัก และ workflow ระหว่างโมดูล — ดูทั้งหมดก่อนเริ่มใช้งาน" : "Core data model and workflow across modules"}
        actions={
          <>
            <button className="btn btn-sm"><I.download /> {lang === "th" ? "ส่งออก PDF" : "Export PDF"}</button>
            <button className="btn btn-sm btn-primary"><I.spark /> {lang === "th" ? "เริ่ม Onboarding" : "Start onboarding"}</button>
          </>
        }
      />

      {/* Hero — workflow overview */}
      <WorkflowHero lang={lang} />

      {/* Tabs */}
      <div style={{ display: "flex", gap: 6, marginTop: 28, marginBottom: 16, padding: 4, background: "var(--glass)", border: "1px solid var(--line)", borderRadius: 12, width: "fit-content" }}>
        {[
          { id: "data",  th: "Data Model",       en: "Data Model"        },
          { id: "flow",  th: "Approval Flow",    en: "Approval Flow"     },
          { id: "stack", th: "โครงสร้างทีม",      en: "Roles & Access"    },
          { id: "tables",th: "ตารางตัวอย่าง",     en: "Sample Records"    },
        ].map((t) => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{
              padding: "8px 14px", borderRadius: 8, border: 0, cursor: "pointer",
              background: tab === t.id ? "var(--glass-3)" : "transparent",
              color: tab === t.id ? "var(--ink)" : "var(--ink-soft)",
              fontSize: 13, fontWeight: 500,
            }}>{lang === "th" ? t.th : t.en}</button>
        ))}
      </div>

      {tab === "data"   && <DataModel lang={lang} />}
      {tab === "flow"   && <ApprovalFlow lang={lang} />}
      {tab === "stack"  && <RolesAccess lang={lang} />}
      {tab === "tables" && <SampleTables lang={lang} />}
    </div>
  );
}

// ── Workflow hero (animated) ─────────────────────────────────
function WorkflowHero({ lang }) {
  const nodes = [
    { id: "boq",  x:  60, y: 110, label: lang === "th" ? "BOQ /\nใบเสนอราคา" : "BOQ /\nQuotation",     color: "#6f86ff" },
    { id: "ctr",  x: 250, y: 110, label: lang === "th" ? "สัญญา\nลูกค้า" : "Contract\n(Client)",         color: "#8a5aff" },
    { id: "pr",   x: 440, y:  40, label: "PR",                                                            color: "#4ade80" },
    { id: "po",   x: 600, y:  40, label: "PO →\n" + (lang === "th" ? "รับของ" : "Receive"),               color: "#4ade80" },
    { id: "inv",  x: 760, y: 110, label: lang === "th" ? "คลังหน้างาน" : "Site Inventory",                color: "#f6c97c" },
    { id: "sub",  x: 440, y: 180, label: lang === "th" ? "ผู้รับเหมา\nช่วง" : "Subcontractor",            color: "#ffb84d" },
    { id: "prog", x: 600, y: 180, label: lang === "th" ? "งวดงาน" : "Progress",                          color: "#6f86ff" },
    { id: "bil",  x: 920, y: 110, label: lang === "th" ? "วางบิล /\nภาษี / เงินประกัน" : "Billing /\nTax / Retention", color: "#ff6b8a" },
  ];
  const links = [
    ["boq","ctr"],["ctr","pr"],["pr","po"],["po","inv"],
    ["ctr","sub"],["sub","prog"],["prog","bil"],["inv","prog"],
  ];
  const getNode = (id) => nodes.find(n => n.id === id);

  return (
    <div className="card" style={{ position: "relative", overflow: "hidden" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
        <div>
          <div className="micro">End-to-End Workflow</div>
          <h2 className="h2" style={{ marginTop: 6 }}>{lang === "th" ? "เส้นทางเอกสารตั้งแต่ใบเสนอราคาถึงเก็บเงิน" : "From quotation to collection — full document flow"}</h2>
        </div>
        <div style={{ display: "flex", gap: 12, fontSize: 11.5 }}>
          {[["#6f86ff","Document"],["#4ade80","Procurement"],["#ffb84d","Subcon"],["#ff6b8a","Finance"]].map(([c,l])=>(
            <span key={l} style={{ display:"inline-flex", alignItems:"center", gap:6, color:"var(--ink-soft)"}}>
              <span style={{width:8,height:8,borderRadius:2,background:c}}/>{l}
            </span>
          ))}
        </div>
      </div>

      <div style={{ overflowX: "auto" }}>
        <svg viewBox="0 0 1040 260" style={{ width: "100%", minWidth: 900, height: "auto", display: "block" }}>
          <defs>
            <marker id="arrowhead" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto">
              <path d="M0,0 L8,4 L0,8 L2,4 z" fill="rgba(180,200,255,0.6)" />
            </marker>
            <linearGradient id="lineGrad" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="rgba(120,144,255,0.1)" />
              <stop offset="100%" stopColor="rgba(120,144,255,0.7)" />
            </linearGradient>
          </defs>

          {links.map(([a,b], i) => {
            const A = getNode(a), B = getNode(b);
            return (
              <g key={i}>
                <path d={`M${A.x+62} ${A.y} C ${(A.x+B.x)/2+30} ${A.y}, ${(A.x+B.x)/2-30} ${B.y}, ${B.x-2} ${B.y}`}
                      stroke="url(#lineGrad)" strokeWidth="1.5" fill="none" markerEnd="url(#arrowhead)"
                      strokeDasharray="2000" style={{ animation: `drawLine 1.6s ${i*0.12}s cubic-bezier(.2,.7,.2,1) both` }} />
              </g>
            );
          })}

          {nodes.map((n, i) => (
            <g key={n.id} transform={`translate(${n.x},${n.y})`} style={{ animation: `fadeUp .5s ${0.2 + i*0.08}s both` }}>
              <rect x="-2" y="-26" width="128" height="52" rx="10" fill="rgba(255,255,255,0.05)" stroke={n.color} strokeOpacity="0.45" strokeWidth="1" />
              <circle cx="124" cy="0" r="3" fill={n.color}>
                <animate attributeName="r" values="3;5;3" dur="2.4s" repeatCount="indefinite" begin={`${i*0.2}s`} />
              </circle>
              {n.label.split("\n").map((line, j) => (
                <text key={j} x="62" y={-4 + j*14} textAnchor="middle" fill="rgba(238,241,255,0.92)" fontSize="11.5" fontWeight="500" fontFamily="Inter, IBM Plex Sans Thai Looped, sans-serif">{line}</text>
              ))}
            </g>
          ))}
        </svg>
      </div>
    </div>
  );
}

// ── Data model (ER-style) ────────────────────────────────────
function DataModel({ lang }) {
  const tables = [
    { id: "Project",       color: "#6f86ff", fields: ["id", "code", "name", "client_id (→Customer)", "site_address", "value", "start_date", "due_date", "status"] },
    { id: "Customer",      color: "#8a5aff", fields: ["id", "name", "tax_id", "address", "phone", "type (บุคคล/นิติบุคคล)"] },
    { id: "BOQ_Quotation", color: "#6f86ff", fields: ["id", "code", "project_id", "version", "issue_date", "valid_days", "total", "status"] },
    { id: "BOQ_Item",      color: "#6f86ff", fields: ["id", "boq_id (→BOQ)", "group_no", "no", "desc", "qty", "unit", "mat_price", "lab_price", "ref_material_id"] },
    { id: "Material",      color: "#f6c97c", fields: ["id", "code", "name", "unit", "price", "category", "vendor_id (→Vendor)"] },
    { id: "Vendor",        color: "#f6c97c", fields: ["id", "name", "contact", "tax_id", "credit_terms"] },
    { id: "PR",            color: "#4ade80", fields: ["id", "code", "project_id", "requester_id", "date", "status", "approver_id"] },
    { id: "PR_Item",       color: "#4ade80", fields: ["id", "pr_id (→PR)", "material_id", "qty", "unit_price"] },
    { id: "PO",            color: "#4ade80", fields: ["id", "code", "pr_id (→PR)", "vendor_id", "date", "delivery_date", "total", "status"] },
    { id: "GoodsReceipt",  color: "#4ade80", fields: ["id", "po_id (→PO)", "received_date", "qty_received", "received_by"] },
    { id: "Inventory",     color: "#f6c97c", fields: ["id", "material_id", "project_id", "qty_on_hand", "reorder_pt", "last_movement"] },
    { id: "Contract",      color: "#8a5aff", fields: ["id", "code", "kind (Owner/Subcon)", "party_id", "project_id", "value", "retention_pct", "signed_date", "end_date"] },
    { id: "Subcontractor", color: "#ffb84d", fields: ["id", "code", "name", "type", "rating", "tax_id", "phone"] },
    { id: "ProgressPeriod",color: "#6f86ff", fields: ["id", "project_id", "no", "name", "pct", "value", "status", "billed_date"] },
    { id: "Invoice",       color: "#ff6b8a", fields: ["id", "code", "project_id", "period_id (→ProgressPeriod)", "issue_date", "subtotal", "vat", "wht", "retention", "net", "status"] },
    { id: "Retention",     color: "#ff6b8a", fields: ["id", "project_id", "amount_held", "release_date", "released", "status"] },
  ];

  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
        {tables.map((t, i) => (
          <div key={t.id} className="card-tight" style={{
            background: "var(--glass)", border: "1px solid var(--line)",
            borderRadius: 12, padding: 14,
            animation: `fadeUp .4s ${i*0.04}s both`,
            position: "relative", overflow: "hidden",
          }}>
            <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 2, background: t.color, opacity: 0.7 }} />
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: t.color, boxShadow: `0 0 10px ${t.color}` }} />
              <span className="mono" style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)" }}>{t.id}</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {t.fields.map((f, j) => (
                <div key={j} className="mono" style={{
                  fontSize: 11, color: f.includes("→") ? "var(--syk-blue-soft)" : "var(--ink-soft)",
                  padding: "3px 6px", borderRadius: 4,
                  background: j === 0 ? "rgba(120,144,255,0.08)" : "transparent",
                  fontWeight: j === 0 ? 600 : 400,
                }}>
                  {j === 0 && <span style={{ marginRight: 6, color: "var(--gold)" }}>🔑</span>}
                  {f}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div className="card-tight" style={{ marginTop: 16, padding: 16, background: "var(--glass)", border: "1px solid var(--line)", borderRadius: 12, fontSize: 12.5 }}>
        <div className="micro" style={{ marginBottom: 8 }}>{lang === "th" ? "หลักการเก็บข้อมูล" : "Storage principles"}</div>
        <ul style={{ margin: 0, paddingLeft: 18, lineHeight: 1.8, color: "var(--ink-soft)" }}>
          <li>{lang === "th" ? "แยก Master (Material, Vendor, Customer, Subcontractor) ออกจาก Transaction (BOQ, PR, PO, Invoice) เพื่อแก้ราคาแล้วไม่กระทบเอกสารเดิม" : "Separate Master from Transaction data so price updates don't break old documents"}</li>
          <li>{lang === "th" ? "BOQ_Item อ้างอิง material_id แบบไม่บังคับ — ราคาในเอกสารถูก snapshot ณ วันที่ออก" : "BOQ_Item references material_id optionally; price is snapshotted on issue"}</li>
          <li>{lang === "th" ? "ทุกเอกสารผูกกับ project_id เป็นแกนหลัก — ดูประวัติได้จากหน้า Project" : "Every document links to project_id as the spine — drill-down from Project page"}</li>
          <li>{lang === "th" ? "ใช้ status field + audit log (created/updated/approved by, timestamp) เพื่อตามรอย workflow" : "Status fields + audit log for workflow traceability"}</li>
          <li>{lang === "th" ? "ภาษี VAT/WHT/Retention คำนวณตอนออก Invoice — เก็บเป็น field แยกใน Invoice เพื่อ audit ภาษี" : "VAT/WHT/Retention computed at invoice issue, stored as separate fields for tax audit"}</li>
        </ul>
      </div>
    </div>
  );
}

// ── Approval flow swimlane ───────────────────────────────────
function ApprovalFlow({ lang }) {
  const lanes = [
    { id: "qs",   label: lang === "th" ? "ฝ่ายประมาณราคา" : "QS",      color: "#6f86ff" },
    { id: "buy",  label: lang === "th" ? "ฝ่ายจัดซื้อ" : "Procurement", color: "#4ade80" },
    { id: "pm",   label: lang === "th" ? "PM / โฟร์แมน" : "PM / Foreman", color: "#ffb84d" },
    { id: "fin",  label: lang === "th" ? "บัญชี/การเงิน" : "Finance",   color: "#ff6b8a" },
    { id: "exec", label: lang === "th" ? "ผู้บริหาร" : "Executive",      color: "#f6c97c" },
  ];
  const steps = [
    { lane: "qs",   x:  60, label: lang === "th" ? "ทำ BOQ" : "Build BOQ" },
    { lane: "exec", x: 200, label: lang === "th" ? "อนุมัติส่งใบเสนอราคา" : "Approve quotation" },
    { lane: "pm",   x: 340, label: lang === "th" ? "เปิด PR ตามแผน" : "Open PR" },
    { lane: "buy",  x: 480, label: lang === "th" ? "ออก PO ส่งผู้ขาย" : "Issue PO" },
    { lane: "pm",   x: 620, label: lang === "th" ? "ตรวจรับของหน้างาน" : "Goods receipt" },
    { lane: "pm",   x: 760, label: lang === "th" ? "ส่งงานงวด" : "Submit milestone" },
    { lane: "fin",  x: 900, label: lang === "th" ? "วางบิล / VAT" : "Issue invoice" },
  ];
  const laneY = (id) => lanes.findIndex((l) => l.id === id) * 70 + 50;

  return (
    <div className="card" style={{ overflow: "hidden" }}>
      <div className="micro" style={{ marginBottom: 14 }}>{lang === "th" ? "Swimlane: เส้นทางอนุมัติเอกสาร" : "Swimlane: document approval path"}</div>
      <div style={{ overflowX: "auto" }}>
        <svg viewBox="0 0 1020 400" style={{ width: "100%", minWidth: 920, height: 420, display: "block" }}>
          {lanes.map((l, i) => (
            <g key={l.id}>
              <rect x="120" y={i*70 + 20} width="900" height="60" fill={i%2===0 ? "rgba(255,255,255,0.02)" : "transparent"} />
              <line x1="120" y1={i*70 + 80} x2="1020" y2={i*70 + 80} stroke="var(--line)" />
              <text x="110" y={i*70 + 56} textAnchor="end" fill={l.color} fontSize="12" fontWeight="600" fontFamily="Inter, IBM Plex Sans Thai Looped, sans-serif">{l.label}</text>
              <rect x="0" y={i*70 + 36} width="100" height="28" rx="14" fill="rgba(255,255,255,0.04)" stroke={l.color} strokeOpacity="0.3" />
            </g>
          ))}

          {/* Steps */}
          {steps.map((s, i) => {
            const lane = lanes.find((l) => l.id === s.lane);
            return (
              <g key={i} transform={`translate(${s.x}, ${laneY(s.lane)})`} style={{ animation: `fadeUp .5s ${i*0.12}s both` }}>
                <rect x="-50" y="-22" width="100" height="44" rx="22" fill="rgba(255,255,255,0.06)" stroke={lane.color} strokeOpacity="0.5" />
                <text x="0" y="4" textAnchor="middle" fill="var(--ink)" fontSize="10.5" fontWeight="500" fontFamily="Inter, IBM Plex Sans Thai Looped, sans-serif">{s.label}</text>
                <text x="0" y="-10" textAnchor="middle" fill={lane.color} fontSize="9" fontWeight="700" fontFamily="JetBrains Mono, monospace">{String(i+1).padStart(2,"0")}</text>
              </g>
            );
          })}

          {/* Arrows */}
          {steps.slice(0,-1).map((s, i) => {
            const n = steps[i+1];
            const y1 = laneY(s.lane), y2 = laneY(n.lane);
            const x1 = s.x + 50, x2 = n.x - 50;
            const mx = (x1 + x2) / 2;
            return (
              <path key={i} d={`M${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`}
                    stroke="rgba(180,200,255,0.45)" strokeWidth="1.5" fill="none"
                    markerEnd="url(#arrowhead2)"
                    strokeDasharray="800" style={{ animation: `drawLine 1.4s ${0.4 + i*0.12}s cubic-bezier(.2,.7,.2,1) both` }} />
            );
          })}
          <defs>
            <marker id="arrowhead2" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto">
              <path d="M0,0 L8,4 L0,8 L2,4 z" fill="rgba(180,200,255,0.7)" />
            </marker>
          </defs>
        </svg>
      </div>
    </div>
  );
}

// ── Roles & access ────────────────────────────────────────────
function RolesAccess({ lang }) {
  const roles = [
    { name: lang === "th" ? "เจ้าของบริษัท / ผู้บริหาร" : "Executive",     access: ["Dashboard", "อนุมัติทุกเอกสาร", "งบประมาณ", "รายงาน"], color: "#f6c97c" },
    { name: lang === "th" ? "ผู้จัดการโครงการ (PM)" : "Project Manager",   access: ["โครงการ", "งวดงาน", "PR/PO", "Subcon", "Inventory"], color: "#6f86ff" },
    { name: lang === "th" ? "ฝ่ายประมาณราคา (QS)" : "Quantity Surveyor",  access: ["BOQ", "Quotation", "Material DB"], color: "#8a5aff" },
    { name: lang === "th" ? "ฝ่ายจัดซื้อ" : "Procurement",                 access: ["PR/PO", "Vendor", "Material DB"], color: "#4ade80" },
    { name: lang === "th" ? "ฝ่ายบัญชี/การเงิน" : "Finance",               access: ["Invoice", "VAT/WHT", "Retention", "รายงานภาษี"], color: "#ff6b8a" },
    { name: lang === "th" ? "โฟร์แมน / หน้างาน" : "Foreman",                access: ["Inventory", "Goods Receipt", "Progress"], color: "#ffb84d" },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
      {roles.map((r, i) => (
        <div key={i} className="card-tight" style={{ padding: 16, border: "1px solid var(--line)", borderRadius: 14, background: "var(--glass)", animation: `fadeUp .4s ${i*0.05}s both` }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: `${r.color}20`, border: `1px solid ${r.color}55`, display: "flex", alignItems: "center", justifyContent: "center", color: r.color }}>
              <I.user />
            </div>
            <div style={{ fontWeight: 600, fontSize: 13.5 }}>{r.name}</div>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
            {r.access.map((a, j) => (
              <span key={j} className="chip" style={{ fontSize: 10.5 }}>{a}</span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Sample data tables ────────────────────────────────────────
function SampleTables({ lang }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="card">
        <div className="h3" style={{ marginBottom: 12 }}>Material — {lang === "th" ? "ตัวอย่างฐานราคาวัสดุ" : "price catalog sample"}</div>
        <table className="table">
          <thead><tr>
            <th>Code</th><th>{lang==="th"?"รายการ":"Item"}</th><th>{lang==="th"?"หน่วย":"Unit"}</th><th style={{textAlign:"right"}}>{lang==="th"?"ราคา":"Price"}</th><th>{lang==="th"?"หมวด":"Category"}</th><th>Vendor</th>
          </tr></thead>
          <tbody>
            {MATERIALS.slice(0, 8).map((m) => (
              <tr key={m.code} className="row-int">
                <td className="mono ink-soft" style={{ fontSize: 12 }}>{m.code}</td>
                <td>{m.name}</td>
                <td className="ink-soft">{m.unit}</td>
                <td className="mono" style={{ textAlign:"right" }}>{fmtTHB(m.price)}</td>
                <td><span className="chip">{m.cat}</span></td>
                <td className="ink-soft">{m.vendor}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="card">
        <div className="h3" style={{ marginBottom: 12 }}>Project — {lang === "th" ? "โครงการที่กำลังดำเนินการ" : "active projects"}</div>
        <table className="table">
          <thead><tr>
            <th>Code</th><th>{lang==="th"?"ชื่อโครงการ":"Name"}</th><th>{lang==="th"?"พื้นที่":"Site"}</th><th style={{textAlign:"right"}}>{lang==="th"?"มูลค่า":"Value"}</th><th>{lang==="th"?"คืบหน้า":"Progress"}</th><th>Status</th>
          </tr></thead>
          <tbody>
            {PROJECTS.map((p) => (
              <tr key={p.code} className="row-int">
                <td className="mono ink-soft" style={{ fontSize: 12 }}>{p.code}</td>
                <td>{p.name}</td>
                <td className="ink-soft">{p.site}</td>
                <td className="mono" style={{ textAlign:"right" }}>{fmtTHB(p.value)}</td>
                <td style={{ width: 140 }}>
                  <div style={{ display:"flex", alignItems:"center", gap: 8 }}>
                    <div className="prog" style={{ flex: 1 }}><span style={{ width: `${p.progress*100}%` }} /></div>
                    <span className="mono ink-soft" style={{ fontSize: 11 }}>{fmtPct(p.progress)}</span>
                  </div>
                </td>
                <td><StatusBadge status={p.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.ArchitecturePage = ArchitecturePage;
