// ════════════════════════════════════════════════════════════════
//  THE GOLDEN TRIANGLE 🔺 — PM (เวลา) + QS (เงิน) + จัดซื้อ (ต้นทุนวัสดุ)
//  รวมฟีเจอร์ข้ามทีม: Cash Flow Forecast · Procurement Calendar · Suppliers
// ════════════════════════════════════════════════════════════════

// ── Supplier + price-history manager (localStorage) ──
window.SupplierManager = window.SupplierManager || (function () {
  const KEY = 'syk-suppliers-v1';
  const listeners = new Set();
  const load = () => { try { return JSON.parse(localStorage.getItem(KEY) || '[]'); } catch { return []; } };
  const save = (a) => { localStorage.setItem(KEY, JSON.stringify(a)); listeners.forEach(fn => { try { fn(); } catch {} }); };
  return {
    list() { return load(); },
    add(data) { const a = load(); a.unshift({ id: 'SUP_' + Date.now().toString(36), materials: [], ...data }); save(a); },
    update(id, patch) { save(load().map(s => s.id === id ? { ...s, ...patch } : s)); },
    remove(id) { save(load().filter(s => s.id !== id)); },
    // บันทึกราคาวัสดุ + เก็บประวัติ
    setMaterial(id, mat) {
      const a = load();
      const s = a.find(x => x.id === id); if (!s) return;
      s.materials = s.materials || [];
      const ex = s.materials.find(m => m.name === mat.name);
      const entry = { ...mat, updated_at: new Date().toISOString() };
      if (ex) { ex.history = ex.history || []; if (ex.price !== mat.price) ex.history.unshift({ price: ex.price, at: ex.updated_at }); Object.assign(ex, entry); }
      else s.materials.push({ ...entry, history: [] });
      save(a);
    },
    // หาราคาล่าสุดของวัสดุ (auto-fill)
    bestPrice(name) {
      const all = [];
      load().forEach(s => (s.materials || []).forEach(m => { if (m.name && name && m.name.toLowerCase().includes(name.toLowerCase())) all.push({ supplier: s.name, ...m }); }));
      all.sort((a, b) => (a.price || 0) - (b.price || 0));
      return all[0] || null;
    },
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
  };
})();

// ── Material lead-time (วันสั่งล่วงหน้า) ตามคีย์เวิร์ดหมวดงาน ──
const GT_LEADTIME = [
  { kw: ['เหล็ก', 'โครงสร้าง', 'steel', 'rebar', 'เสาเข็ม'], days: 10 },
  { kw: ['คอนกรีต', 'concrete', 'ปูน', 'ฐานราก', 'คาน', 'เสา'], days: 3 },
  { kw: ['อิฐ', 'ก่อ', 'ฉาบ', 'ผนัง', 'มวลเบา'], days: 5 },
  { kw: ['กระเบื้อง', 'พื้น', 'tile', 'แกรนิต'], days: 14 },
  { kw: ['หลังคา', 'roof', 'แป', 'ลอน'], days: 14 },
  { kw: ['ประตู', 'หน้าต่าง', 'door', 'window', 'upvc'], days: 21 },
  { kw: ['ไฟฟ้า', 'electric', 'สาย', 'ตู้', 'mdb'], days: 14 },
  { kw: ['ประปา', 'สุขภัณฑ์', 'ท่อ', 'plumb', 'sanitary'], days: 14 },
  { kw: ['แอร์', 'hvac', 'ปรับอากาศ'], days: 21 },
  { kw: ['สี', 'paint', 'กันซึม'], days: 5 },
];
function gtLeadDays(text) {
  const t = (text || '').toLowerCase();
  for (const r of GT_LEADTIME) if (r.kw.some(k => t.includes(k.toLowerCase()))) return r.days;
  return 7;
}

const gtFmt = (n) => { n = Number(n) || 0; const s = n < 0 ? '-' : ''; const v = Math.abs(n); if (v >= 1e6) return s + (v / 1e6).toFixed(2) + 'M'; if (v >= 1e3) return s + (v / 1e3).toFixed(0) + 'K'; return s + Math.round(v).toLocaleString(); };
const gtDMY = (iso) => { const m = String(iso || '').match(/^(\d{4})-(\d{2})-(\d{2})/); return m ? `${m[3]}/${m[2]}/${m[1]}` : '—'; };
const gtMonthLabel = (ym) => { const [y, m] = ym.split('-'); const mn = ['ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.']; return `${mn[Number(m) - 1]} ${y}`; };

function gtContracts(code) {
  try { return JSON.parse(localStorage.getItem('syk-contracts-v1') || '[]').filter(c => c.project_code === code); } catch { return []; }
}

function GoldenTrianglePage({ lang }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const [tab, setTab] = React.useState('cashflow');
  const [, force] = React.useState(0);
  React.useEffect(() => {
    const h = () => force(x => x + 1);
    window.addEventListener('syk-active', h);
    const un = window.SupplierManager.subscribe(h);
    return () => { window.removeEventListener('syk-active', h); un(); };
  }, []);

  const projects = window.ProjectManager?.list?.() || [];
  const activeCode = (window.SykActive && window.SykActive.get()) || projects[0]?.code;
  const project = projects.find(p => p.code === activeCode) || projects[0] || null;

  return (
    <div className="anim-fadein">
      <PageHeader
        title={T('🔺 Golden Triangle — PM × QS × จัดซื้อ', 'Golden Triangle')}
        subtitle={T('สามประสาน: เวลา (PM) + เงิน (QS) + ต้นทุนวัสดุ (จัดซื้อ)', 'Time + Money + Material cost')}
        actions={projects.length > 0 && (
          <select className="field" style={{ width: 260, height: 36, fontSize: 12 }} value={project?.code || ''}
            onChange={(e) => { window.SykActive?.set(e.target.value); force(x => x + 1); }}>
            {projects.map(p => <option key={p.code} value={p.code}>{p.code} — {p.name}</option>)}
          </select>
        )}
      />

      {/* 3-corner summary */}
      <TriangleSummary project={project} lang={lang} />

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, padding: 4, background: 'var(--glass)', border: '1px solid var(--line)', borderRadius: 12, width: 'fit-content', flexWrap: 'wrap' }}>
        {[
          { id: 'cashflow', th: '💰 กระแสเงินสด (PM×QS)', en: 'Cash Flow' },
          { id: 'procurement', th: '📦 ปฏิทินจัดซื้อ (จัดซื้อ×PM)', en: 'Procurement Calendar' },
          { id: 'suppliers', th: '🏭 ฐาน Supplier (QS×จัดซื้อ)', en: 'Suppliers' },
        ].map(tt => (
          <button key={tt.id} onClick={() => setTab(tt.id)}
            style={{ padding: '7px 14px', borderRadius: 8, border: 0, cursor: 'pointer', fontSize: 12.5, fontWeight: 600,
              background: tab === tt.id ? 'var(--gold-soft, #c89858)' : 'transparent', color: tab === tt.id ? '#1a1208' : 'var(--ink-soft)' }}>
            {T(tt.th, tt.en)}
          </button>
        ))}
      </div>

      {!project ? (
        <div className="card" style={{ textAlign: 'center', padding: 40, color: 'var(--ink-mute)' }}>{T('ยังไม่มีโครงการ', 'No project')}</div>
      ) : tab === 'cashflow' ? <CashFlowTab project={project} lang={lang} />
        : tab === 'procurement' ? <ProcurementTab project={project} lang={lang} />
        : <SuppliersTab lang={lang} />}
    </div>
  );
}

// ── สามมุม: สรุปสถานะ ──
function TriangleSummary({ project, lang }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  if (!project) return null;
  const code = project.code;
  const contracts = gtContracts(code);
  const owner = contracts.find(c => c.kind === 'Owner-Contractor');
  const subs = contracts.filter(c => c.kind === 'Subcontract');
  const actuals = (window.ProgressManager && window.ProgressManager.get(code)) || {};

  // PM: % schedule progress
  const ms = (owner?.milestones || []);
  const planPct = ms.reduce((s, m) => s + (Number(m.pct) || 0), 0);
  const actPct = ms.reduce((s, m) => { const ap = (actuals[m.no] || {}).actual_pct; return s + (Number(m.pct) || 0) * ((ap != null ? ap : 0) / 100); }, 0);
  // QS: contract value vs sub commitments
  const contractValue = Number(owner?.value) || Number(project.value) || 0;
  const subValue = subs.reduce((s, c) => s + (Number(c.value) || 0), 0);
  // จัดซื้อ: รายการที่ใกล้ถึงกำหนดสั่ง (จาก procurement)
  const corners = [
    { icon: '🕐', label: T('PM · เวลา', 'Time'), v: `${actPct.toFixed(0)}% / ${planPct.toFixed(0)}%`, sub: T('ทำได้ / ตามแผน', 'actual/plan'), color: '#6f86ff' },
    { icon: '💰', label: T('QS · เงิน', 'Money'), v: gtFmt(contractValue), sub: T('มูลค่าสัญญา', 'contract value'), color: '#22c55e' },
    { icon: '📦', label: T('จัดซื้อ · วัสดุ', 'Material'), v: gtFmt(subValue), sub: T('ผูกผู้รับเหมาช่วง', 'subcontracted'), color: '#f472b6' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 14 }} className="agents-grid">
      {corners.map((c, i) => (
        <div key={i} className="card card-tight" style={{ borderTop: `3px solid ${c.color}`, textAlign: 'center' }}>
          <div style={{ fontSize: 22 }}>{c.icon}</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-mute)', marginTop: 2 }}>{c.label}</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700, color: c.color }}>{c.v}</div>
          <div style={{ fontSize: 9.5, color: 'var(--ink-mute)' }}>{c.sub}</div>
        </div>
      ))}
    </div>
  );
}

// ── TAB 1: Cash Flow Forecast ──
function CashFlowTab({ project, lang }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const code = project.code;
  const contracts = gtContracts(code);
  const owner = contracts.find(c => c.kind === 'Owner-Contractor');
  const subs = contracts.filter(c => c.kind === 'Subcontract');

  // events keyed by month: รับ (in) จากงวดลูกค้า, จ่าย (out) จากงวดผู้รับเหมาช่วง
  const months = {};
  const addEv = (date, key, amt) => {
    if (!date) return; const ym = String(date).slice(0, 7); if (!/^\d{4}-\d{2}$/.test(ym)) return;
    months[ym] = months[ym] || { in: 0, out: 0 };
    months[ym][key] += Number(amt) || 0;
  };
  (owner?.milestones || []).forEach(m => addEv(m.due_date, 'in', m.amount));
  subs.forEach(c => (c.milestones || []).forEach(m => addEv(m.due_date, 'out', m.amount)));

  const keys = Object.keys(months).sort();
  let cum = 0;
  const rows = keys.map(ym => { const r = months[ym]; const net = r.in - r.out; cum += net; return { ym, in: r.in, out: r.out, net, cum }; });
  const totIn = rows.reduce((s, r) => s + r.in, 0), totOut = rows.reduce((s, r) => s + r.out, 0);
  const maxAbs = Math.max(1, ...rows.map(r => Math.max(r.in, r.out)));

  return (
    <div className="card">
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ fontSize: 16 }}>💰</span>
        <h3 className="h2" style={{ margin: 0 }}>{T('พยากรณ์กระแสเงินสดรายเดือน', 'Monthly Cash Flow Forecast')}</h3>
      </div>
      {rows.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 30, color: 'var(--ink-mute)', fontSize: 12.5 }}>
          {T('ยังไม่มีข้อมูล — ต้องมีงวดงานที่กำหนดวันส่ง (กรอกจำนวนวัน/วันที่ในหน้าสัญญา)', 'No milestone due dates yet — set durations in Contracts')}
        </div>
      ) : (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginBottom: 12 }}>
            <div style={{ padding: 10, background: 'var(--bg-2)', borderRadius: 8 }}><div style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{T('รวมเงินเข้า (ลูกค้า)', 'Total in')}</div><div className="mono" style={{ fontWeight: 700, color: '#22c55e' }}>{gtFmt(totIn)}</div></div>
            <div style={{ padding: 10, background: 'var(--bg-2)', borderRadius: 8 }}><div style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{T('รวมเงินออก (ช่วง)', 'Total out')}</div><div className="mono" style={{ fontWeight: 700, color: '#f472b6' }}>{gtFmt(totOut)}</div></div>
            <div style={{ padding: 10, background: 'var(--bg-2)', borderRadius: 8 }}><div style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{T('สุทธิสะสม', 'Net cumulative')}</div><div className="mono" style={{ fontWeight: 700, color: cum >= 0 ? '#22c55e' : '#ff6b8a' }}>{gtFmt(cum)}</div></div>
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table className="table" style={{ fontSize: 12 }}>
              <thead><tr>
                <th>{T('เดือน', 'Month')}</th>
                <th style={{ textAlign: 'right', color: '#22c55e' }}>{T('เข้า', 'In')}</th>
                <th style={{ textAlign: 'right', color: '#f472b6' }}>{T('ออก', 'Out')}</th>
                <th style={{ textAlign: 'right' }}>{T('สุทธิ', 'Net')}</th>
                <th style={{ textAlign: 'right' }}>{T('สะสม', 'Cum')}</th>
                <th style={{ width: 160 }}></th>
              </tr></thead>
              <tbody>
                {rows.map(r => (
                  <tr key={r.ym}>
                    <td style={{ fontWeight: 600 }}>{gtMonthLabel(r.ym)}</td>
                    <td className="mono" style={{ textAlign: 'right', color: '#22c55e' }}>{r.in ? gtFmt(r.in) : '—'}</td>
                    <td className="mono" style={{ textAlign: 'right', color: '#f472b6' }}>{r.out ? gtFmt(r.out) : '—'}</td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: r.net >= 0 ? '#22c55e' : '#ff6b8a' }}>{r.net >= 0 ? '+' : ''}{gtFmt(r.net)}</td>
                    <td className="mono" style={{ textAlign: 'right', color: r.cum >= 0 ? 'var(--ink)' : '#ff6b8a' }}>{gtFmt(r.cum)}</td>
                    <td>
                      <div style={{ display: 'flex', gap: 1, height: 16, alignItems: 'center' }}>
                        <div style={{ width: `${(r.in / maxAbs) * 70}px`, height: 10, background: '#22c55e', borderRadius: 2 }} />
                        <div style={{ width: `${(r.out / maxAbs) * 70}px`, height: 10, background: '#f472b6', borderRadius: 2 }} />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 8 }}>
            💡 {T('เงินเข้า = งวดลูกค้า · เงินออก = งวดผู้รับเหมาช่วง (ตามวันกำหนดส่งในสัญญา) — ถ้าสุทธิสะสมติดลบเดือนใด แปลว่าต้องสำรองเงินทุนหมุนเวียน', 'Net negative months = need working capital')}
          </div>
        </>
      )}
    </div>
  );
}

// ── TAB 2: Procurement Calendar ──
function ProcurementTab({ project, lang }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const code = project.code;
  const contracts = gtContracts(code);
  const owner = contracts.find(c => c.kind === 'Owner-Contractor');
  const today = new Date(); today.setHours(0, 0, 0, 0);

  // สำหรับแต่ละงวด: ต้องการวัสดุเข้าหน้างานวัน "เริ่มงวด" → ต้องสั่งซื้อก่อน lead time
  const items = (owner?.milestones || []).map(m => {
    const needBy = m.start_date || m.due_date || '';
    const lead = gtLeadDays(m.name + ' ' + (m.linked_groups || []).join(' '));
    let orderBy = '';
    if (needBy) { const d = new Date(needBy + 'T00:00:00'); d.setDate(d.getDate() - lead); orderBy = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }
    const obDate = orderBy ? new Date(orderBy + 'T00:00:00') : null;
    const daysLeft = obDate ? Math.round((obDate - today) / 86400000) : null;
    return { no: m.no, name: m.name, needBy, lead, orderBy, daysLeft };
  }).filter(x => x.needBy).sort((a, b) => (a.orderBy || '').localeCompare(b.orderBy || ''));

  const statusOf = (d) => d == null ? { c: 'var(--ink-mute)', t: '—' }
    : d < 0 ? { c: '#ff6b8a', t: T('เลยกำหนดสั่ง!', 'OVERDUE') }
    : d <= 7 ? { c: '#fbbf24', t: T(`สั่งใน ${d} วัน`, `${d}d`) }
    : { c: '#22c55e', t: T(`อีก ${d} วัน`, `${d}d`) };

  return (
    <div className="card">
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ fontSize: 16 }}>📦</span>
        <h3 className="h2" style={{ margin: 0 }}>{T('ปฏิทินสั่งซื้อวัสดุ (อิงแผนงวดงาน)', 'Procurement Calendar')}</h3>
      </div>
      {items.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 30, color: 'var(--ink-mute)', fontSize: 12.5 }}>
          {T('ต้องมีงวดงานที่ตั้งวันเริ่ม/กำหนดส่ง (กรอกจำนวนวันในหน้าสัญญา) ก่อน', 'Set milestone schedule in Contracts first')}
        </div>
      ) : (
        <>
          <div style={{ overflowX: 'auto' }}>
            <table className="table" style={{ fontSize: 12 }}>
              <thead><tr>
                <th style={{ width: 40 }}>#</th>
                <th>{T('งวดงาน / วัสดุหลัก', 'Milestone')}</th>
                <th style={{ width: 90, textAlign: 'center' }}>{T('Lead time', 'Lead')}</th>
                <th style={{ width: 110, textAlign: 'center' }}>{T('ต้องสั่งภายใน', 'Order by')}</th>
                <th style={{ width: 110, textAlign: 'center' }}>{T('ของถึงหน้างาน', 'Need on site')}</th>
                <th style={{ width: 120, textAlign: 'center' }}>{T('สถานะ', 'Status')}</th>
              </tr></thead>
              <tbody>
                {items.map(it => {
                  const st = statusOf(it.daysLeft);
                  return (
                    <tr key={it.no}>
                      <td className="mono" style={{ fontWeight: 700, color: 'var(--gold-soft,#c89858)' }}>{it.no}</td>
                      <td style={{ fontWeight: 500 }}>{it.name}</td>
                      <td className="mono" style={{ textAlign: 'center', color: 'var(--ink-mute)' }}>{it.lead} {T('วัน', 'd')}</td>
                      <td className="mono" style={{ textAlign: 'center', fontWeight: 700, color: st.c }}>{gtDMY(it.orderBy)}</td>
                      <td className="mono" style={{ textAlign: 'center' }}>{gtDMY(it.needBy)}</td>
                      <td style={{ textAlign: 'center' }}><span style={{ fontWeight: 700, color: st.c }}>{st.t}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 8 }}>
            💡 {T('Lead time = เวลาที่วัสดุใช้กว่าจะถึงหน้างาน · "ต้องสั่งภายใน" = วันเริ่มงวด − lead time → สีแดง = เลยกำหนดสั่งแล้ว ต้องรีบ', 'Order-by = milestone start − lead time')}
          </div>
        </>
      )}
    </div>
  );
}

// ── TAB 3: Suppliers ──
function SuppliersTab({ lang }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const [, force] = React.useState(0);
  const [adding, setAdding] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', category: '', phone: '', credit_terms: '', matName: '', matUnit: '', matPrice: '' });
  React.useEffect(() => { const un = window.SupplierManager.subscribe(() => force(x => x + 1)); return un; }, []);
  const suppliers = window.SupplierManager.list();

  const addSupplier = () => {
    if (!form.name.trim()) return;
    window.SupplierManager.add({ name: form.name, category: form.category, phone: form.phone, credit_terms: form.credit_terms });
    setForm({ name: '', category: '', phone: '', credit_terms: '', matName: '', matUnit: '', matPrice: '' });
    setAdding(false);
  };

  const inp = { width: '100%', padding: '8px 10px', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 6, color: 'var(--ink)', fontSize: 12.5 };

  return (
    <div className="card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 16 }}>🏭</span>
          <h3 className="h2" style={{ margin: 0 }}>{T('ฐานข้อมูล Supplier + ประวัติราคา', 'Supplier database')}</h3>
        </div>
        <button className="btn btn-sm btn-primary" onClick={() => setAdding(a => !a)}>+ {T('เพิ่ม Supplier', 'Add')}</button>
      </div>

      {adding && (
        <div style={{ padding: 12, background: 'var(--bg-2)', borderRadius: 8, marginBottom: 12, display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 8 }}>
          <input placeholder={T('ชื่อ Supplier *', 'Name *')} value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} style={inp} />
          <input placeholder={T('หมวด เช่น เหล็ก', 'Category')} value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))} style={inp} />
          <input placeholder={T('โทร', 'Phone')} value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} style={inp} />
          <div style={{ display: 'flex', gap: 6 }}>
            <input placeholder={T('เครดิต เช่น 30 วัน', 'Credit')} value={form.credit_terms} onChange={e => setForm(f => ({ ...f, credit_terms: e.target.value }))} style={inp} />
            <button className="btn btn-sm btn-primary" onClick={addSupplier} style={{ whiteSpace: 'nowrap' }}>✓</button>
          </div>
        </div>
      )}

      {suppliers.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 30, color: 'var(--ink-mute)', fontSize: 12.5 }}>
          {T('ยังไม่มี supplier — เพิ่มเพื่อเก็บราคาวัสดุจริงและประวัติราคา (ไว้ auto-fill แทนราคากลาง)', 'No suppliers yet')}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {suppliers.map(s => <SupplierCard key={s.id} s={s} lang={lang} inp={inp} />)}
        </div>
      )}
    </div>
  );
}

function SupplierCard({ s, lang, inp }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const [m, setM] = React.useState({ name: '', unit: '', price: '' });
  const addMat = () => { if (!m.name.trim()) return; window.SupplierManager.setMaterial(s.id, { name: m.name, unit: m.unit, price: Number(m.price) || 0 }); setM({ name: '', unit: '', price: '' }); };
  return (
    <div style={{ padding: 12, background: 'var(--bg-2)', borderRadius: 8, borderLeft: '3px solid var(--gold-soft, #c89858)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
        <span style={{ fontSize: 16 }}>🏭</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 13 }}>{s.name}</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>{[s.category, s.phone, s.credit_terms && `เครดิต ${s.credit_terms}`].filter(Boolean).join(' · ') || '—'}</div>
        </div>
        <button className="btn btn-sm btn-ghost" onClick={() => { if (confirm(T('ลบ supplier นี้?', 'Delete?'))) window.SupplierManager.remove(s.id); }} style={{ color: 'var(--rose)' }}>×</button>
      </div>
      {(s.materials || []).length > 0 && (
        <table className="table" style={{ fontSize: 11.5, marginBottom: 8 }}>
          <thead><tr><th>{T('วัสดุ', 'Material')}</th><th style={{ width: 60 }}>{T('หน่วย', 'Unit')}</th><th style={{ width: 90, textAlign: 'right' }}>{T('ราคา', 'Price')}</th><th style={{ width: 120 }}>{T('ประวัติ', 'History')}</th></tr></thead>
          <tbody>
            {s.materials.map((mat, i) => (
              <tr key={i}>
                <td>{mat.name}</td>
                <td style={{ color: 'var(--ink-mute)' }}>{mat.unit}</td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{(mat.price || 0).toLocaleString()}</td>
                <td style={{ fontSize: 9.5, color: 'var(--ink-mute)' }}>{(mat.history || []).slice(0, 2).map(h => (h.price || 0).toLocaleString()).join(' ← ') || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
      <div style={{ display: 'flex', gap: 6 }}>
        <input placeholder={T('+ วัสดุ', 'material')} value={m.name} onChange={e => setM(x => ({ ...x, name: e.target.value }))} style={{ ...inp, flex: 2 }} />
        <input placeholder={T('หน่วย', 'unit')} value={m.unit} onChange={e => setM(x => ({ ...x, unit: e.target.value }))} style={{ ...inp, flex: 1 }} />
        <input placeholder={T('ราคา', 'price')} type="number" value={m.price} onChange={e => setM(x => ({ ...x, price: e.target.value }))} style={{ ...inp, flex: 1, textAlign: 'right' }} />
        <button className="btn btn-sm" onClick={addMat}>+</button>
      </div>
    </div>
  );
}

window.GoldenTrianglePage = GoldenTrianglePage;
