// Project Overview — Single Source of Truth สำหรับทุกหน้า
// โครงการต้องสร้างที่หน้านี้เท่านั้น (เก็บใน localStorage + sync window.PROJECTS)
// หน้าอื่น (BOQ/Contract/PR-PO/Drawings) จะใช้ list นี้เป็น dropdown

const PHASE_DEFS = {
  quotation:    { th: 'ใบเสนอราคา',       en: 'Quotation',    color: '#94a3b8', icon: '📝', order: 1 },
  contract:     { th: 'ทำสัญญาแล้ว',      en: 'Contracted',   color: '#a78bfa', icon: '📜', order: 2 },
  construction: { th: 'ดำเนินการก่อสร้าง', en: 'Construction', color: '#6f86ff', icon: '🏗️', order: 3 },
  handover:     { th: 'ส่งมอบงาน',         en: 'Handover',     color: '#fbbf24', icon: '📦', order: 4 },
  warranty:     { th: 'ประกันผลงาน',       en: 'Warranty',     color: '#4ade80', icon: '🛡️', order: 5 },
  expired:      { th: 'หมดประกัน',         en: 'Expired',      color: '#64748b', icon: '🏁', order: 6 },
};

// ─── Project Types — 3-letter abbreviations for code generation ──
const PROJECT_TYPES = [
  { code: 'HSE', th: 'บ้านพักอาศัย',        en: 'House' },
  { code: 'COM', th: 'อาคารพาณิชย์',        en: 'Commercial Building' },
  { code: 'APT', th: 'อพาร์ตเมนต์-คอนโด',   en: 'Apartment / Condo' },
  { code: 'OFF', th: 'อาคารสำนักงาน',       en: 'Office Building' },
  { code: 'FAC', th: 'โรงงาน',              en: 'Factory' },
  { code: 'WAR', th: 'คลังสินค้า',          en: 'Warehouse' },
  { code: 'RES', th: 'โรงแรม-รีสอร์ท',      en: 'Hotel / Resort' },
  { code: 'SCH', th: 'โรงเรียน-สถานศึกษา',  en: 'School' },
  { code: 'HOS', th: 'โรงพยาบาล',           en: 'Hospital' },
  { code: 'REN', th: 'ปรับปรุง-ต่อเติม',    en: 'Renovation / Extension' },
  { code: 'INT', th: 'ตกแต่งภายใน',         en: 'Interior' },
  { code: 'LND', th: 'ภูมิทัศน์-จัดสวน',    en: 'Landscape' },
  { code: 'INF', th: 'งานสาธารณูปโภค',      en: 'Infrastructure' },
  { code: 'RD',  th: 'งานถนน-ลานคอนกรีต',   en: 'Road / Pavement' },
  { code: 'STR', th: 'งานโครงสร้างเฉพาะ',   en: 'Structure Only' },
  { code: 'MEP', th: 'งานระบบ M&E',         en: 'MEP Systems' },
  { code: 'OTH', th: 'อื่นๆ (กำหนดเอง)',    en: 'Other (Custom)' },
];
window.PROJECT_TYPES = PROJECT_TYPES;

// ─── ProjectManager: localStorage-backed single source of truth ──
window.ProjectManager = (function() {
  const STORE_KEY = 'syk-projects-master';
  const RECORDS_KEY = 'syk-project-records';  // { [code]: { boqs:[], contracts:[], prpos:[], drawings:[] } }
  const listeners = new Set();

  function load() {
    try { return JSON.parse(localStorage.getItem(STORE_KEY) || '[]'); } catch { return []; }
  }
  function save(arr) {
    localStorage.setItem(STORE_KEY, JSON.stringify(arr));
    window.PROJECTS = arr;
    listeners.forEach(fn => { try { fn(arr); } catch {} });
  }
  function loadRecords() {
    try { return JSON.parse(localStorage.getItem(RECORDS_KEY) || '{}'); } catch { return {}; }
  }
  function saveRecords(obj) {
    localStorage.setItem(RECORDS_KEY, JSON.stringify(obj));
  }

  // Generate code: CNT-XXX-YY-MM-NO
  // XXX = 3-letter project type abbreviation
  // YY  = Buddhist year 2-digit
  // MM  = month
  // NO  = running counter for same YY-MM (across all types)
  function generateCode(typeCode) {
    const list = load();
    const d = new Date();
    const yy = String((d.getFullYear() + 543) % 100).padStart(2, '0');
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const prefix = `CNT-`;
    const ymPattern = `-${yy}-${mm}-`;
    // Count all CNT-* projects with same YY-MM (any type)
    const sameMonth = list.filter(p => (p.code || '').startsWith(prefix) && (p.code || '').includes(ymPattern));
    const no = String(sameMonth.length + 1).padStart(2, '0');
    return `${prefix}${typeCode || 'OTH'}-${yy}-${mm}-${no}`;
  }

  return {
    list() { return load(); },
    get(code) { return load().find(p => p.code === code); },
    generateCode,
    create(data) {
      const list = load();
      // Auto-generate code if not provided
      if (!data.code) {
        data.code = generateCode(data.project_type || 'OTH');
      }
      // Prevent dup code
      if (list.find(p => p.code === data.code)) throw new Error('รหัสโครงการนี้มีอยู่แล้ว: ' + data.code);
      const newProject = {
        code: data.code,
        project_type: data.project_type || 'OTH',
        project_type_label: data.project_type_label || '',
        name: data.name || '',
        client: data.client || '',
        site: data.site || '',
        value: Number(data.value) || 0,
        vat_included: !!data.vat_included,
        progress: 0,
        status: 'pending',
        phase: data.phase || 'quotation',
        start: data.start || '',
        due: data.due || '',
        contract_signed: data.contract_signed || null,
        handover_date: data.handover_date || null,
        duration_years: Number(data.duration_years) || 0,
        duration_months: Number(data.duration_months) || 0,
        warranty_years: Number(data.warranty_years) || 0,
        warranty_months: Number(data.warranty_months) || 0,
        warranty_end: data.warranty_end || null,
        notes: data.notes || '',
        created_at: new Date().toISOString(),
      };
      list.unshift(newProject);
      save(list);
      return newProject;
    },
    update(code, patch) {
      const list = load().map(p => p.code === code ? { ...p, ...patch, code } : p);
      save(list);
    },
    remove(code) {
      save(load().filter(p => p.code !== code));
      // Also remove related records
      const recs = loadRecords();
      delete recs[code];
      saveRecords(recs);
    },
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },

    // Records: BOQs/Contracts/PR-PO/Drawings per project
    getRecords(code) {
      const all = loadRecords();
      return all[code] || { boqs: [], contracts: [], prpos: [], drawings: [] };
    },
    addRecord(code, type, item) {
      const all = loadRecords();
      if (!all[code]) all[code] = { boqs: [], contracts: [], prpos: [], drawings: [] };
      const id = type.toUpperCase() + '-' + Date.now().toString().slice(-6);
      all[code][type].unshift({ id, ...item, created_at: new Date().toISOString() });
      saveRecords(all);
      return all[code];
    },
    removeRecord(code, type, id) {
      const all = loadRecords();
      if (all[code]?.[type]) {
        all[code][type] = all[code][type].filter(x => x.id !== id);
        saveRecords(all);
      }
    },

    // Bootstrap window.PROJECTS on app load
    bootstrap() {
      const list = load();
      window.PROJECTS = list;
      return list;
    },
  };
})();

// Bootstrap immediately so PROJECTS is available
window.ProjectManager.bootstrap();

// ─── Main Page Component ────────────────────────────────────────
function ProjectOverviewPage({ lang }) {
  const [projects, setProjects] = useState(() => window.ProjectManager.list());
  const [phaseFilter, setPhaseFilter] = useState('all');
  const [searchQ, setSearchQ] = useState('');
  const [expanded, setExpanded] = useState(null);
  const [showCreate, setShowCreate] = useState(false);
  const [editing, setEditing] = useState(null);
  const toast = useToast();

  useEffect(() => {
    const unsub = window.ProjectManager.subscribe(setProjects);
    return unsub;
  }, []);

  const counts = useMemo(() => {
    const c = { all: projects.length };
    Object.keys(PHASE_DEFS).forEach(k => { c[k] = 0; });
    projects.forEach(p => { if (c[p.phase] !== undefined) c[p.phase]++; });
    return c;
  }, [projects]);

  const filtered = useMemo(() => {
    const q = searchQ.trim().toLowerCase();
    return projects
      .filter(p => phaseFilter === 'all' || p.phase === phaseFilter)
      .filter(p => !q || p.code.toLowerCase().includes(q) || (p.name || '').toLowerCase().includes(q) || (p.site || '').toLowerCase().includes(q) || (p.client || '').toLowerCase().includes(q))
      .sort((a, b) => {
        const ao = PHASE_DEFS[a.phase]?.order || 99;
        const bo = PHASE_DEFS[b.phase]?.order || 99;
        if (ao !== bo) return ao - bo;
        return (b.value || 0) - (a.value || 0);
      });
  }, [projects, phaseFilter, searchQ]);

  const handleSave = (data) => {
    try {
      if (editing) {
        window.ProjectManager.update(editing.code, data);
        toast(lang === 'th' ? 'อัปเดตโครงการแล้ว' : 'Project updated', 'success');
      } else {
        const p = window.ProjectManager.create(data);
        toast(lang === 'th' ? `สร้างโครงการ ${p.code} แล้ว` : `Created ${p.code}`, 'success');
      }
      setShowCreate(false);
      setEditing(null);
    } catch (err) {
      toast(err.message || 'Failed', 'danger');
    }
  };

  const handleDelete = (code) => {
    if (!confirm(lang === 'th' ? `ลบโครงการ ${code} และข้อมูลที่เกี่ยวข้องทั้งหมด?` : `Delete ${code} and all records?`)) return;
    window.ProjectManager.remove(code);
    toast(lang === 'th' ? 'ลบแล้ว' : 'Deleted', 'success');
    setExpanded(null);
  };

  // EMPTY STATE — no projects yet
  if (projects.length === 0) {
    return (
      <div className="anim-fadein">
        <PageHeader
          title={lang === 'th' ? 'ภาพรวมโครงการทั้งหมด' : 'Project Overview'}
          subtitle={lang === 'th' ? 'ยังไม่มีโครงการ — สร้างโครงการแรกเพื่อเริ่มใช้งาน' : 'No projects yet — create the first one'}
        />
        <div className="card" style={{ textAlign: 'center', padding: '60px 20px' }}>
          <div style={{ fontSize: 72, marginBottom: 16 }}>📋</div>
          <h2 style={{ margin: '0 0 8px', fontSize: 20, fontWeight: 700 }}>
            {lang === 'th' ? 'เริ่มจากการสร้างโครงการแรก' : 'Start by creating your first project'}
          </h2>
          <p style={{ color: 'var(--ink-soft)', fontSize: 13, maxWidth: 460, margin: '0 auto 24px', lineHeight: 1.6 }}>
            {lang === 'th'
              ? 'โครงการที่สร้างที่นี่จะเป็นข้อมูลหลัก ทุกใบเสนอราคา สัญญา PR/PO และไฟล์แบบก่อสร้าง ต้องผูกกับโครงการที่อยู่ในรายการนี้เท่านั้น'
              : 'Projects created here become the single source of truth. All BOQs, Contracts, PR/PO, and Drawings must reference a project from this list.'}
          </p>
          <button className="btn btn-primary" onClick={() => setShowCreate(true)} style={{ fontSize: 14, padding: '12px 24px' }}>
            <I.plus /> {lang === 'th' ? 'สร้างโครงการแรก' : 'Create First Project'}
          </button>
          <div style={{ marginTop: 24, padding: 16, background: 'var(--glass-2)', borderRadius: 10, maxWidth: 540, margin: '24px auto 0', textAlign: 'left' }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>💡 {lang === 'th' ? 'หรือสร้างข้อมูลตัวอย่างเพื่อทดลอง' : 'Or seed sample data to explore'}</div>
            <button className="btn btn-sm" onClick={() => { seedSampleData(); toast(lang === 'th' ? 'สร้างข้อมูลตัวอย่างแล้ว' : 'Sample data created', 'success'); }}>
              <I.bolt /> {lang === 'th' ? 'สร้างโครงการตัวอย่าง 3 โครงการ' : 'Seed 3 sample projects'}
            </button>
          </div>
        </div>
        {showCreate && <CreateProjectModal lang={lang} onClose={() => setShowCreate(false)} onSave={handleSave} />}
      </div>
    );
  }

  return (
    <div className="anim-fadein">
      <PageHeader
        title={lang === 'th' ? 'ภาพรวมโครงการทั้งหมด' : 'Project Overview'}
        subtitle={lang === 'th'
          ? `${projects.length} โครงการ · ทุกข้อมูลในระบบ (BOQ, สัญญา, PR/PO, แบบก่อสร้าง) อ้างอิงจากโครงการในหน้านี้`
          : `${projects.length} projects · Single source of truth`}
        actions={<>
          <button className="btn btn-sm btn-primary" onClick={() => { setEditing(null); setShowCreate(true); }}>
            <I.plus /> {lang === 'th' ? 'สร้างโครงการใหม่' : 'New Project'}
          </button>
        </>}
      />

      {/* PHASE FILTER STRIP */}
      <div className="card card-tight" style={{ padding: 14, marginBottom: 14 }}>
        <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
          <PhaseChip id="all" label={lang === 'th' ? 'ทั้งหมด' : 'All'} count={counts.all}
            color="#6f86ff" icon="📋" active={phaseFilter === 'all'} onClick={() => setPhaseFilter('all')} />
          {Object.entries(PHASE_DEFS).map(([id, d]) => (
            <PhaseChip key={id} id={id} label={lang === 'th' ? d.th : d.en} count={counts[id]}
              color={d.color} icon={d.icon} active={phaseFilter === id} onClick={() => setPhaseFilter(id)} />
          ))}
        </div>
        <div style={{ position: 'relative' }}>
          <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-mute)' }}><I.search /></span>
          <input className="field" placeholder={lang === 'th' ? 'ค้นหา รหัส / ชื่อ / เจ้าของ / สถานที่...' : 'Search...'}
            value={searchQ} onChange={(e) => setSearchQ(e.target.value)} style={{ paddingLeft: 36, height: 36 }} />
        </div>
      </div>

      {/* PIPELINE BAR */}
      <div className="card" style={{ marginBottom: 14, padding: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
          <span style={{ fontSize: 16 }}>🌊</span>
          <h3 className="h2" style={{ margin: 0, fontSize: 14 }}>{lang === 'th' ? 'Pipeline ตลอดวงจรชีวิต' : 'Lifecycle Pipeline'}</h3>
        </div>
        <div style={{ display: 'flex', gap: 4, height: 32 }}>
          {Object.entries(PHASE_DEFS).map(([id, d]) => {
            const count = counts[id] || 0;
            return (
              <div key={id} onClick={() => setPhaseFilter(id)} title={`${lang === 'th' ? d.th : d.en}: ${count}`}
                style={{
                  flex: Math.max(0.5, count || 0.5), background: d.color + '40', borderTop: `2px solid ${d.color}`,
                  borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
                  cursor: 'pointer', transition: '.2s', fontSize: 11,
                  opacity: count === 0 ? 0.4 : 1,
                }}>
                <span>{d.icon}</span>
                <strong style={{ color: d.color }}>{count}</strong>
              </div>
            );
          })}
        </div>
        <div style={{ display: 'flex', gap: 4, marginTop: 4, fontSize: 9, color: 'var(--ink-mute)' }}>
          {Object.entries(PHASE_DEFS).map(([id, d]) => (
            <div key={id} style={{ flex: Math.max(0.5, counts[id] || 0.5), textAlign: 'center', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {lang === 'th' ? d.th : d.en}
            </div>
          ))}
        </div>
      </div>

      {/* PROJECT LIST */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map(p => (
          <ProjectRow key={p.code} project={p} lang={lang}
            expanded={expanded === p.code}
            onToggle={() => setExpanded(expanded === p.code ? null : p.code)}
            onEdit={() => { setEditing(p); setShowCreate(true); }}
            onDelete={() => handleDelete(p.code)}
            onNav={(page) => window.__appNav?.(page)} />
        ))}
        {filtered.length === 0 && (
          <div className="card" style={{ textAlign: 'center', padding: 60, color: 'var(--ink-mute)' }}>
            <div style={{ fontSize: 36 }}>🔍</div>
            <div style={{ marginTop: 12 }}>{lang === 'th' ? 'ไม่พบโครงการที่ค้นหา' : 'No matching projects'}</div>
          </div>
        )}
      </div>

      {showCreate && (
        <CreateProjectModal lang={lang} initial={editing}
          onClose={() => { setShowCreate(false); setEditing(null); }}
          onSave={handleSave} />
      )}
    </div>
  );
}

function PhaseChip({ label, count, color, icon, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px',
      background: active ? color : color + '15',
      border: '1px solid ' + (active ? color : color + '40'),
      color: active ? '#fff' : color, borderRadius: 8, cursor: 'pointer',
      fontSize: 12, fontWeight: 600, transition: '.15s',
    }}>
      <span style={{ fontSize: 14 }}>{icon}</span>
      <span>{label}</span>
      <span style={{ padding: '1px 6px', borderRadius: 4, background: active ? 'rgba(255,255,255,0.25)' : 'rgba(255,255,255,0.08)', fontSize: 11 }}>{count}</span>
    </button>
  );
}

function ProjectRow({ project: p, expanded, onToggle, onEdit, onDelete, onNav, lang }) {
  const phase = PHASE_DEFS[p.phase] || PHASE_DEFS.quotation;
  const progressPct = Math.round((p.progress || 0) * 100);

  let warrantyInfo = null;
  if (p.phase === 'warranty' && p.warranty_end) {
    const days = Math.ceil((new Date(p.warranty_end) - Date.now()) / 86400000);
    warrantyInfo = { days, urgent: days < 30 };
  }

  return (
    <div className="card" style={{
      padding: 0, overflow: 'hidden',
      borderLeft: `3px solid ${phase.color}`,
      transition: '.2s',
    }}>
      <div onClick={onToggle} style={{
        display: 'grid', gridTemplateColumns: '40px 110px 1fr auto auto auto auto', gap: 14,
        alignItems: 'center', padding: '14px 18px', cursor: 'pointer',
        background: expanded ? 'var(--glass-2)' : 'transparent',
      }}>
        <div style={{ fontSize: 24 }}>{phase.icon}</div>
        <div className="mono" style={{ fontSize: 12, color: phase.color, fontWeight: 700 }}>{p.code}</div>
        <div>
          <div style={{ fontWeight: 600, fontSize: 13.5 }}>{p.name || '—'}</div>
          <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>
            {p.project_type && p.project_type !== 'OTH' && (
              <span style={{ display: 'inline-block', padding: '1px 6px', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 3, color: 'var(--syk-blue)', fontWeight: 600, fontFamily: 'var(--font-mono)', fontSize: 10, marginRight: 6 }}>
                {p.project_type}
              </span>
            )}
            {p.project_type === 'OTH' && p.project_type_label && (
              <span style={{ display: 'inline-block', padding: '1px 6px', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 3, color: 'var(--ink-soft)', fontSize: 10, marginRight: 6 }}>
                {p.project_type_label}
              </span>
            )}
            {p.client && `👤 ${p.client} · `}📍 {p.site || '—'} · {fmtTHBshort(p.value || 0)}{p.vat_included ? ' (+VAT)' : ''}
          </div>
        </div>
        <div style={{ textAlign: 'center' }}>
          <span className="chip" style={{ background: phase.color + '25', color: phase.color, fontWeight: 700, border: `1px solid ${phase.color}40` }}>
            {lang === 'th' ? phase.th : phase.en}
          </span>
          {warrantyInfo && (
            <div style={{ fontSize: 10, color: warrantyInfo.urgent ? 'var(--rose)' : 'var(--emerald)', marginTop: 3, fontWeight: 600 }}>
              {warrantyInfo.days > 0
                ? (lang === 'th' ? `เหลือ ${warrantyInfo.days} วัน` : `${warrantyInfo.days}d left`)
                : (lang === 'th' ? '⚠ หมดประกัน' : '⚠ Expired')}
            </div>
          )}
        </div>
        <div style={{ minWidth: 120, textAlign: 'right' }}>
          <div style={{ fontSize: 10, color: 'var(--ink-mute)', marginBottom: 4 }}>{lang === 'th' ? 'ความคืบหน้า' : 'Progress'}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ flex: 1, height: 6, background: 'var(--glass-3)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: progressPct + '%', background: phase.color, borderRadius: 999, transition: 'width .4s' }} />
            </div>
            <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: phase.color, minWidth: 32, textAlign: 'right' }}>{progressPct}%</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
          <button className="btn btn-sm btn-ghost" onClick={onEdit} title="Edit"><I.edit /></button>
          <button className="btn btn-sm btn-ghost" onClick={onDelete} title="Delete" style={{ color: 'var(--rose)' }}><I.trash /></button>
        </div>
        <div style={{ color: 'var(--ink-mute)', transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)', transition: '.2s' }}>
          <I.chev dir="down" />
        </div>
      </div>

      {expanded && <ProjectDetails project={p} onNav={onNav} lang={lang} />}
    </div>
  );
}

function ProjectDetails({ project: p, onNav, lang }) {
  const [tab, setTab] = useState('summary');
  const [records, setRecords] = useState(() => window.ProjectManager.getRecords(p.code));
  const [showAddRecord, setShowAddRecord] = useState(null); // 'boqs' | 'contracts' | ...
  const toast = useToast();

  const refresh = () => setRecords(window.ProjectManager.getRecords(p.code));

  const handleAddRecord = (type, data) => {
    window.ProjectManager.addRecord(p.code, type, data);
    refresh();
    setShowAddRecord(null);
    toast(lang === 'th' ? 'เพิ่มรายการแล้ว' : 'Record added', 'success');
  };

  const handleRemoveRecord = (type, id) => {
    if (!confirm(lang === 'th' ? 'ลบรายการนี้?' : 'Delete this record?')) return;
    window.ProjectManager.removeRecord(p.code, type, id);
    refresh();
    toast(lang === 'th' ? 'ลบแล้ว' : 'Deleted', 'success');
  };

  const tabs = [
    { id: 'summary',   th: 'สรุป',         en: 'Summary',   count: null },
    { id: 'boqs',      th: 'ใบเสนอราคา',   en: 'BOQ',       count: (records.boqs || []).length,      type: 'boq' },
    { id: 'contracts', th: 'สัญญา',        en: 'Contracts', count: (records.contracts || []).length, type: 'contracts' },
    { id: 'drawings',  th: 'แบบก่อสร้าง',  en: 'Drawings',  count: (records.drawings || []).length,  type: 'drawings' },
    { id: 'prpos',     th: 'PR / PO',     en: 'PR / PO',    count: (records.prpos || []).length,     type: 'procurement' },
  ];

  return (
    <div style={{ borderTop: '1px solid var(--line)', background: 'rgba(0,0,0,0.15)' }}>
      <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', padding: '0 8px', flexWrap: 'wrap' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{
              padding: '10px 14px', background: 'transparent', border: 0, cursor: 'pointer',
              color: tab === t.id ? 'var(--ink)' : 'var(--ink-soft)',
              borderBottom: tab === t.id ? '2px solid var(--syk-blue-soft)' : '2px solid transparent',
              fontSize: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6,
            }}>
            {lang === 'th' ? t.th : t.en}
            {t.count !== null && <span style={{ padding: '1px 6px', background: 'var(--glass-3)', borderRadius: 4, fontSize: 10 }}>{t.count}</span>}
          </button>
        ))}
      </div>

      <div style={{ padding: 16 }}>
        {tab === 'summary' && <SummaryTab project={p} records={records} onNav={onNav} lang={lang} />}
        {tab === 'boqs' && <BOQRecordsTab project={p} records={records.boqs || []} lang={lang}
          onAdd={() => setShowAddRecord('boqs')}
          onRemove={(id) => handleRemoveRecord('boqs', id)}
          onNav={onNav} />}
        {tab === 'contracts' && <ContractRecordsTab project={p} records={records.contracts || []} lang={lang}
          onAdd={() => setShowAddRecord('contracts')}
          onRemove={(id) => handleRemoveRecord('contracts', id)}
          onNav={onNav} />}
        {tab === 'drawings' && <DrawingRecordsTab project={p} records={records.drawings || []} lang={lang}
          onAdd={() => setShowAddRecord('drawings')}
          onRemove={(id) => handleRemoveRecord('drawings', id)}
          onNav={onNav} />}
        {tab === 'prpos' && <PRPORecordsTab project={p} records={records.prpos || []} lang={lang}
          onAdd={() => setShowAddRecord('prpos')}
          onRemove={(id) => handleRemoveRecord('prpos', id)}
          onNav={onNav} />}
      </div>

      {showAddRecord && (
        <AddRecordModal type={showAddRecord} project={p} lang={lang}
          onClose={() => setShowAddRecord(null)}
          onSave={(data) => handleAddRecord(showAddRecord, data)} />
      )}
    </div>
  );
}

// ─── Summary Tab ─────────────────────────────────────────────
function SummaryTab({ project: p, records, onNav, lang }) {
  const phase = PHASE_DEFS[p.phase] || PHASE_DEFS.quotation;
  return (
    <div>
      {/* Lifecycle timeline */}
      <div style={{ marginBottom: 14 }}>
        <div className="micro" style={{ marginBottom: 10 }}>{lang === 'th' ? 'ขั้นตอนวงจรชีวิต' : 'Lifecycle stages'}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {Object.entries(PHASE_DEFS).map(([id, d], i) => {
            const reached = d.order <= phase.order;
            const current = id === p.phase;
            return (
              <React.Fragment key={id}>
                <div style={{
                  flex: 1, padding: '8px 10px', borderRadius: 8,
                  background: current ? d.color : reached ? d.color + '20' : 'var(--glass-2)',
                  color: current ? '#fff' : reached ? d.color : 'var(--ink-mute)',
                  border: '1px solid ' + (current ? d.color : reached ? d.color + '40' : 'var(--line)'),
                  textAlign: 'center', transition: '.2s',
                }}>
                  <div style={{ fontSize: 16 }}>{d.icon}</div>
                  <div style={{ fontSize: 10, fontWeight: 600, marginTop: 2 }}>{lang === 'th' ? d.th : d.en}</div>
                </div>
                {i < Object.keys(PHASE_DEFS).length - 1 && (
                  <div style={{ width: 16, height: 2, background: reached ? d.color + '60' : 'var(--line)', flexShrink: 0 }} />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Key info grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 14 }}>
        <InfoCell label={lang === 'th' ? 'มูลค่าสัญญา' : 'Contract value'}
          value={fmtTHBshort(p.value || 0) + (p.vat_included ? ' (รวม VAT)' : '')}
          accent="#1e3a5f" />
        <InfoCell label={lang === 'th' ? 'เจ้าของโครงการ' : 'Client'} value={p.client || '—'} />
        {p.contract_signed && <InfoCell label={lang === 'th' ? 'วันเริ่มสัญญา' : 'Contract start'} value={isoToDDMMYY(p.contract_signed)} accent="#a78bfa" />}
        {p.handover_date && <InfoCell label={lang === 'th' ? 'วันสิ้นสุดสัญญา' : 'Contract end'} value={isoToDDMMYY(p.handover_date)} accent="#fbbf24" />}
        {(p.duration_years > 0 || p.duration_months > 0) && (
          <InfoCell label={lang === 'th' ? 'ระยะเวลาสัญญา' : 'Duration'}
            value={[
              (p.duration_years > 0 ? `${p.duration_years} ${lang === 'th' ? 'ปี' : 'y'}` : ''),
              (p.duration_months > 0 ? `${p.duration_months} ${lang === 'th' ? 'เดือน' : 'm'}` : '')
            ].filter(Boolean).join(' ')} />
        )}
        {p.warranty_end && <InfoCell label={lang === 'th' ? 'วันหมดประกัน' : 'Warranty end'} value={isoToDDMMYY(p.warranty_end)} accent="#4ade80" />}
        {p.notes && <InfoCell label={lang === 'th' ? 'หมายเหตุ' : 'Notes'} value={p.notes} />}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        <QuickLink icon="📄" label="BOQ"      count={(records.boqs || []).length}      lang={lang} />
        <QuickLink icon="📜" label={lang === 'th' ? 'สัญญา' : 'Contracts'} count={(records.contracts || []).length} lang={lang} />
        <QuickLink icon="📐" label={lang === 'th' ? 'แบบก่อสร้าง' : 'Drawings'} count={(records.drawings || []).length} lang={lang} />
        <QuickLink icon="🛒" label="PR / PO"  count={(records.prpos || []).length} lang={lang} />
      </div>
    </div>
  );
}

function InfoCell({ label, value, accent }) {
  return (
    <div style={{ padding: 10, background: 'var(--glass-2)', borderRadius: 8 }}>
      <div className="micro" style={{ fontSize: 10 }}>{label}</div>
      <div style={{ marginTop: 4, fontWeight: 600, color: accent || 'var(--ink)', fontSize: 12, wordBreak: 'break-word' }}>{value}</div>
    </div>
  );
}

function QuickLink({ icon, label, count, lang }) {
  return (
    <div style={{ padding: 14, background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 22 }}>{icon}</span>
        <span style={{ fontSize: 18, fontWeight: 700, color: 'var(--syk-blue-soft)' }}>{count}</span>
      </div>
      <div style={{ fontSize: 11, color: 'var(--ink-soft)', fontWeight: 600, marginTop: 6 }}>{label}</div>
    </div>
  );
}

// ─── Records Tabs (BOQ, Contracts, Drawings, PR/PO) ──────────
function RecordHeader({ title, count, lang, onAdd, onNav, page }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
      <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>
        {count === 0 ? (lang === 'th' ? `ยังไม่มี${title}` : `No ${title}`) : (lang === 'th' ? `${count} รายการ` : `${count} records`)}
      </span>
      <div style={{ display: 'flex', gap: 6 }}>
        <button className="btn btn-sm btn-primary" onClick={onAdd}>
          <I.plus /> {lang === 'th' ? 'เพิ่ม' : 'Add'}
        </button>
        {page && (
          <button className="btn btn-sm" onClick={() => onNav(page)}>
            <I.edit /> {lang === 'th' ? 'แก้ไขที่หน้าหลัก' : 'Edit in main page'}
          </button>
        )}
      </div>
    </div>
  );
}

function RecordItem({ children, onRemove }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'center',
      padding: '10px 14px', background: 'var(--glass)', borderRadius: 8, border: '1px solid var(--line)',
      marginBottom: 6,
    }}>
      <div>{children}</div>
      <button className="btn btn-sm btn-ghost" onClick={onRemove} style={{ color: 'var(--rose)' }}><I.trash /></button>
    </div>
  );
}

function EmptyState({ icon, message, lang }) {
  return (
    <div style={{ textAlign: 'center', padding: 30, color: 'var(--ink-mute)' }}>
      <div style={{ fontSize: 32 }}>{icon}</div>
      <div style={{ marginTop: 8, fontSize: 13 }}>{message}</div>
    </div>
  );
}

function BOQRecordsTab({ records, lang, onAdd, onRemove, onNav }) {
  return (
    <div>
      <RecordHeader title="BOQ" count={records.length} lang={lang} onAdd={onAdd} onNav={onNav} page="boq" />
      {records.length === 0 ? <EmptyState icon="📄" message={lang === 'th' ? 'ยังไม่มีใบเสนอราคา' : 'No BOQ yet'} lang={lang} /> :
        records.map(r => (
          <RecordItem key={r.id} onRemove={() => onRemove(r.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--syk-blue-soft)', fontWeight: 700 }}>{r.id}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{r.title || (lang === 'th' ? 'ใบเสนอราคา' : 'BOQ')}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>
                  {r.date || '—'} · {r.items_count || 0} {lang === 'th' ? 'รายการ' : 'items'} · {r.status || 'draft'}
                </div>
              </div>
              <div className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{fmtTHBshort(r.total || 0)}</div>
            </div>
          </RecordItem>
        ))}
    </div>
  );
}

function ContractRecordsTab({ records, lang, onAdd, onRemove, onNav }) {
  return (
    <div>
      <RecordHeader title={lang === 'th' ? 'สัญญา' : 'Contracts'} count={records.length} lang={lang} onAdd={onAdd} onNav={onNav} page="contracts" />
      {records.length === 0 ? <EmptyState icon="📜" message={lang === 'th' ? 'ยังไม่มีสัญญา' : 'No contracts'} lang={lang} /> :
        records.map(r => (
          <RecordItem key={r.id} onRemove={() => onRemove(r.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--syk-blue-soft)', fontWeight: 700 }}>{r.id}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{r.party || '—'}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>
                  {r.kind || 'Owner-Contractor'} · {r.signed || '—'} → {r.end || '—'}
                </div>
              </div>
              <div className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{fmtTHBshort(r.value || 0)}</div>
            </div>
          </RecordItem>
        ))}
    </div>
  );
}

function DrawingRecordsTab({ records, lang, onAdd, onRemove, onNav }) {
  return (
    <div>
      <RecordHeader title={lang === 'th' ? 'แบบก่อสร้าง' : 'Drawings'} count={records.length} lang={lang} onAdd={onAdd} onNav={onNav} page="drawings" />
      {records.length === 0 ? <EmptyState icon="📐" message={lang === 'th' ? 'ยังไม่มีแบบก่อสร้าง' : 'No drawings'} lang={lang} /> :
        records.map(r => (
          <RecordItem key={r.id} onRemove={() => onRemove(r.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--syk-blue-soft)', fontWeight: 700 }}>{r.id}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{r.name || '—'}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>
                  {r.discipline || 'Architecture'} · Rev. {r.revision || 'A'} · {r.scale || '—'}
                </div>
              </div>
              {r.file_name && <span className="chip">{r.file_name}</span>}
            </div>
          </RecordItem>
        ))}
    </div>
  );
}

function PRPORecordsTab({ records, lang, onAdd, onRemove, onNav }) {
  return (
    <div>
      <RecordHeader title="PR / PO" count={records.length} lang={lang} onAdd={onAdd} onNav={onNav} page="procurement" />
      {records.length === 0 ? <EmptyState icon="🛒" message={lang === 'th' ? 'ยังไม่มี PR/PO' : 'No PR/PO'} lang={lang} /> :
        records.map(r => (
          <RecordItem key={r.id} onRemove={() => onRemove(r.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="chip" style={{ background: r.type === 'PR' ? 'rgba(111,134,255,0.12)' : 'rgba(74,222,128,0.12)', color: r.type === 'PR' ? 'var(--syk-blue-soft)' : 'var(--emerald)' }}>{r.type || 'PR'}</span>
              <span className="mono" style={{ fontSize: 11, color: 'var(--syk-blue-soft)', fontWeight: 700 }}>{r.id}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{r.vendor || r.description || '—'}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>
                  {r.date || '—'} · {r.status || 'pending'}
                </div>
              </div>
              <div className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{fmtTHBshort(r.total || 0)}</div>
            </div>
          </RecordItem>
        ))}
    </div>
  );
}

// ─── Create Project Modal ────────────────────────────────────
function CreateProjectModal({ lang, initial, onClose, onSave }) {
  const isEdit = !!initial;
  const [form, setForm] = useState(() => ({
    code: initial?.code || '',
    project_type: initial?.project_type || 'OTH',
    project_type_label: initial?.project_type_label || '',
    name: initial?.name || '',
    client: initial?.client || '',
    site: initial?.site || '',
    value: initial?.value || 0,
    vat_included: initial?.vat_included || false,
    phase: initial?.phase || 'quotation',
    start: initial?.start || '',
    due: initial?.due || '',
    contract_signed: initial?.contract_signed || '',
    handover_date: initial?.handover_date || '',
    duration_years: initial?.duration_years || 0,
    duration_months: initial?.duration_months || 0,
    warranty_years: initial?.warranty_years || 1,
    warranty_months: initial?.warranty_months || 0,
    warranty_end: initial?.warranty_end || '',
    notes: initial?.notes || '',
  }));
  const toast = useToast();

  // Auto-regenerate code when project_type changes (only in CREATE mode, and only if user hasn't manually edited the code)
  const [codeAutoLocked, setCodeAutoLocked] = useState(true); // true = follow auto-gen
  useEffect(() => {
    if (isEdit || !codeAutoLocked) return;
    const newCode = window.ProjectManager.generateCode(form.project_type);
    if (newCode !== form.code) setForm(f => ({ ...f, code: newCode }));
  }, [form.project_type, codeAutoLocked, isEdit]);

  // Auto-compute warranty_end from handover_date + warranty_years + warranty_months
  const autoWarrantyEnd = useMemo(() => {
    if (!form.handover_date) return '';
    return addPeriod(form.handover_date, Number(form.warranty_years) || 0, Number(form.warranty_months) || 0);
  }, [form.handover_date, form.warranty_years, form.warranty_months]);

  const set = (key, val) => setForm(f => ({ ...f, [key]: val }));

  // ── Duration linking: change any 2 of {contract_signed, handover_date, duration} → compute 3rd ──
  const handleContractSignedChange = (v) => {
    setForm(f => {
      const next = { ...f, contract_signed: v };
      const total = (Number(f.duration_years) || 0) * 12 + (Number(f.duration_months) || 0);
      if (v && total > 0) {
        next.handover_date = addMonths(v, total);
      } else if (v && f.handover_date) {
        const { years, months } = monthsBetween(v, f.handover_date);
        next.duration_years = years;
        next.duration_months = months;
      }
      return next;
    });
  };
  const handleEndChange = (v) => {
    setForm(f => {
      const next = { ...f, handover_date: v };
      const total = (Number(f.duration_years) || 0) * 12 + (Number(f.duration_months) || 0);
      if (v && f.contract_signed) {
        const { years, months } = monthsBetween(f.contract_signed, v);
        next.duration_years = years;
        next.duration_months = months;
      } else if (v && total > 0) {
        next.contract_signed = addMonths(v, -total);
      }
      return next;
    });
  };
  const handleDurationChange = (newYears, newMonths) => {
    setForm(f => {
      const y = Number(newYears) || 0;
      const m = Number(newMonths) || 0;
      const next = { ...f, duration_years: y, duration_months: m };
      const total = y * 12 + m;
      if (total > 0) {
        if (f.contract_signed) {
          next.handover_date = addMonths(f.contract_signed, total);
        } else if (f.handover_date) {
          next.contract_signed = addMonths(f.handover_date, -total);
        }
      }
      return next;
    });
  };

  const submit = () => {
    if (!form.name.trim()) { toast(lang === 'th' ? 'กรุณากรอกชื่อโครงการ' : 'Name required', 'warning'); return; }
    if (!form.client.trim()) { toast(lang === 'th' ? 'กรุณากรอกชื่อเจ้าของโครงการ' : 'Client required', 'warning'); return; }
    if (!form.value || form.value <= 0) { toast(lang === 'th' ? 'กรุณากรอกมูลค่า' : 'Value required', 'warning'); return; }
    onSave({ ...form, warranty_end: autoWarrantyEnd || form.warranty_end });
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div className="card anim-fadein" onClick={(e) => e.stopPropagation()} style={{ width: 'min(720px, 100%)', maxHeight: '90vh', overflowY: 'auto', padding: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
          <div>
            <div className="micro">{isEdit ? (lang === 'th' ? 'แก้ไขโครงการ' : 'Edit Project') : (lang === 'th' ? 'สร้างโครงการใหม่' : 'New Project')}</div>
            <div style={{ fontSize: 20, fontWeight: 700, marginTop: 4 }}>{isEdit ? form.code : (lang === 'th' ? '✨ ข้อมูลโครงการ' : '✨ Project Details')}</div>
          </div>
          <button className="btn btn-sm btn-ghost" onClick={onClose}><I.x /></button>
        </div>

        {/* Section 1: Type & Code */}
        <SectionTitle text={lang === 'th' ? '🏷️ ประเภทงาน & รหัสโครงการ' : '🏷️ Type & Code'} />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 240px', gap: 12, marginBottom: 12 }}>
          <ProjectTypeField lang={lang} value={form.project_type} customLabel={form.project_type_label}
            onChange={(typeCode, label) => { setForm(f => ({ ...f, project_type: typeCode, project_type_label: label || '' })); }} />
          <div>
            <div className="micro" style={{ marginBottom: 6, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>{lang === 'th' ? 'รหัสโครงการ' : 'Project Code'}</span>
              {!isEdit && (
                <button type="button" onClick={() => { setCodeAutoLocked(true); setForm(f => ({ ...f, code: window.ProjectManager.generateCode(f.project_type) })); }}
                  style={{ background: 'transparent', border: 0, color: 'var(--syk-blue)', fontSize: 10, cursor: 'pointer', padding: 0, textTransform: 'none', letterSpacing: 0 }}
                  title="ออกรหัสใหม่อัตโนมัติ">
                  ↻ {lang === 'th' ? 'รีเซ็ตอัตโนมัติ' : 'Auto'}
                </button>
              )}
            </div>
            <input type="text" value={form.code}
              onChange={(e) => { setCodeAutoLocked(false); setForm(f => ({ ...f, code: e.target.value.toUpperCase() })); }}
              disabled={isEdit}
              placeholder="CNT-XXX-69-05-01"
              style={{ width: '100%', padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'var(--font-mono)', opacity: isEdit ? 0.6 : 1 }} />
            <div style={{ fontSize: 10, color: 'var(--ink-mute)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>
              CNT-<span style={{ color: 'var(--syk-blue)' }}>{form.project_type}</span>-YY-MM-NO
            </div>
          </div>
        </div>

        {/* Section 2: Basic */}
        <SectionTitle text={lang === 'th' ? '📋 ข้อมูลพื้นฐาน' : '📋 Basic Info'} />
        <div style={{ marginBottom: 12 }}>
          <FInp label={lang === 'th' ? 'ชื่อโครงการ *' : 'Project Name *'} value={form.name} onChange={(v) => set('name', v)}
            placeholder={lang === 'th' ? 'เช่น บ้านพัก 2 ชั้น คุณ...' : 'e.g. 2-story house...'} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
          <FInp label={lang === 'th' ? 'เจ้าของโครงการ / Client *' : 'Client *'} value={form.client} onChange={(v) => set('client', v)} placeholder={lang === 'th' ? 'ชื่อ-นามสกุล / บริษัท' : 'Name or company'} />
          <FInp label={lang === 'th' ? 'สถานที่ก่อสร้าง / Site' : 'Site location'} value={form.site} onChange={(v) => set('site', v)} placeholder={lang === 'th' ? 'เช่น ลาดพร้าว 71' : 'e.g. district'} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
          <ValueWithVAT lang={lang} value={form.value} vatIncluded={form.vat_included}
            onValueChange={(v) => set('value', Number(v) || 0)}
            onVatChange={(v) => set('vat_included', v)} />
          <FInpSelect label={lang === 'th' ? 'สถานะปัจจุบัน' : 'Current Phase'} value={form.phase} onChange={(v) => set('phase', v)}
            options={Object.entries(PHASE_DEFS).map(([id, d]) => ({ value: id, label: d.icon + ' ' + (lang === 'th' ? d.th : d.en) }))} />
        </div>

        {/* Section 3: Contract Timeline */}
        <SectionTitle text={lang === 'th' ? '📅 ระยะเวลาสัญญา' : '📅 Contract Timeline'} />

        <div style={{ padding: 12, background: 'var(--glass-2)', borderRadius: 8, marginBottom: 12, fontSize: 11, color: 'var(--ink-mute)', display: 'flex', alignItems: 'center', gap: 6 }}>
          💡 {lang === 'th' ? 'กรอก 2 อย่างใน 3 ช่องนี้ (วันเริ่มสัญญา / วันสิ้นสุดสัญญา / ระยะเวลา) อีกช่องจะคำนวณให้อัตโนมัติ' : 'Fill 2 of 3 (contract start / end / duration) — the third auto-fills'}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
          <FInp label={lang === 'th' ? 'วันเริ่มสัญญา' : 'Contract start'} type="date" value={form.contract_signed} onChange={handleContractSignedChange} />
          <FInp label={lang === 'th' ? 'วันสิ้นสุดสัญญา' : 'Contract end'} type="date" value={form.handover_date} onChange={handleEndChange} />
        </div>

        <DurationYMField label={lang === 'th' ? 'ระยะเวลาสัญญา' : 'Contract duration'}
          years={form.duration_years} months={form.duration_months}
          onChange={handleDurationChange} lang={lang} />

        <div style={{ marginBottom: 16 }} />

        {/* Section 4: Warranty */}
        <SectionTitle text={lang === 'th' ? '🛡️ ระยะประกันผลงาน' : '🛡️ Warranty Period'} />

        <div style={{ display: 'grid', gridTemplateColumns: '110px 110px 1fr', gap: 12, marginBottom: 16, alignItems: 'start' }}>
          <div>
            <div className="micro" style={{ marginBottom: 6 }}>{lang === 'th' ? 'จำนวนปี' : 'Years'}</div>
            <input type="number" min="0" max="10" value={form.warranty_years} onChange={(e) => set('warranty_years', Number(e.target.value) || 0)}
              style={{ width: '100%', padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit', textAlign: 'center' }} />
          </div>
          <div>
            <div className="micro" style={{ marginBottom: 6 }}>{lang === 'th' ? 'จำนวนเดือน' : 'Months'}</div>
            <input type="number" min="0" max="11" value={form.warranty_months} onChange={(e) => set('warranty_months', Number(e.target.value) || 0)}
              style={{ width: '100%', padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit', textAlign: 'center' }} />
          </div>
          <div>
            <div className="micro" style={{ marginBottom: 6 }}>{lang === 'th' ? 'วันหมดประกัน (คำนวณอัตโนมัติ)' : 'Warranty end (auto)'}</div>
            <div style={{
              padding: '9px 12px',
              background: autoWarrantyEnd ? 'var(--syk-blue-tint)' : 'var(--glass-2)',
              border: '1px solid ' + (autoWarrantyEnd ? 'rgba(30,58,95,0.3)' : 'var(--line)'),
              borderRadius: 8,
              fontSize: 13, fontFamily: 'var(--font-mono)',
              color: autoWarrantyEnd ? 'var(--syk-blue)' : 'var(--ink-mute)',
              fontWeight: 600, letterSpacing: '0.02em',
            }}>
              {autoWarrantyEnd ? isoToDDMMYY(autoWarrantyEnd) : (lang === 'th' ? 'กรอกวันสิ้นสุดสัญญาก่อน' : 'Enter contract end first')}
            </div>
          </div>
        </div>

        {/* Section 3: Notes */}
        <SectionTitle text={lang === 'th' ? '📝 หมายเหตุ' : '📝 Notes'} />
        <div style={{ marginBottom: 18 }}>
          <textarea value={form.notes} onChange={(e) => set('notes', e.target.value)} rows={3}
            placeholder={lang === 'th' ? 'หมายเหตุเพิ่มเติม...' : 'Additional notes...'}
            style={{ width: '100%', padding: '10px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit', resize: 'vertical' }} />
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn" style={{ flex: 1, justifyContent: 'center' }} onClick={onClose}>{lang === 'th' ? 'ยกเลิก' : 'Cancel'}</button>
          <button className="btn btn-primary" style={{ flex: 1, justifyContent: 'center' }} onClick={submit}>
            <I.check /> {isEdit ? (lang === 'th' ? 'บันทึกการแก้ไข' : 'Save changes') : (lang === 'th' ? 'สร้างโครงการ' : 'Create project')}
          </button>
        </div>
      </div>
    </div>
  );
}

function SectionTitle({ text }) {
  return <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--syk-blue-soft)', marginBottom: 10, letterSpacing: '0.04em' }}>{text}</div>;
}

// ─── Project Type field — dropdown + custom text when "Other" ──
function ProjectTypeField({ lang, value, customLabel, onChange }) {
  const isOther = value === 'OTH';
  return (
    <div>
      <div className="micro" style={{ marginBottom: 6 }}>
        {lang === 'th' ? 'ประเภทงาน *' : 'Project Type *'}
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <select value={value} onChange={(e) => onChange(e.target.value, customLabel)}
          style={{ flex: isOther ? '0 0 200px' : 1, padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit' }}>
          {PROJECT_TYPES.map(t => (
            <option key={t.code} value={t.code}>{t.code} — {lang === 'th' ? t.th : t.en}</option>
          ))}
        </select>
        {isOther && (
          <input type="text" value={customLabel || ''} onChange={(e) => onChange('OTH', e.target.value)}
            placeholder={lang === 'th' ? 'พิมพ์ชื่อประเภทเอง...' : 'Custom type name...'}
            style={{ flex: 1, padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit' }} />
        )}
      </div>
    </div>
  );
}

// ─── Duration field — Separate ปี + เดือน inputs ─────────────
function DurationYMField({ label, years, months, onChange, lang }) {
  const presets = [
    { y: 0, m: 6, label: '6 ' + (lang === 'th' ? 'ด' : 'm') },
    { y: 1, m: 0, label: '1 ' + (lang === 'th' ? 'ป' : 'y') },
    { y: 1, m: 6, label: '1 ' + (lang === 'th' ? 'ป 6 ด' : 'y 6m') },
    { y: 2, m: 0, label: '2 ' + (lang === 'th' ? 'ป' : 'y') },
    { y: 3, m: 0, label: '3 ' + (lang === 'th' ? 'ป' : 'y') },
  ];
  const totalMonths = (Number(years) || 0) * 12 + (Number(months) || 0);

  return (
    <div>
      <div className="micro" style={{ marginBottom: 8 }}>{label}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1.4fr', gap: 8, alignItems: 'start' }}>
        {/* Years */}
        <div>
          <div style={{ position: 'relative' }}>
            <input type="number" min="0" max="20" value={years || ''}
              onChange={(e) => onChange(Number(e.target.value) || 0, Number(months) || 0)}
              placeholder="0"
              style={{ width: '100%', padding: '9px 38px 9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'var(--font-mono)', textAlign: 'right' }} />
            <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 11, color: 'var(--ink-mute)', pointerEvents: 'none' }}>
              {lang === 'th' ? 'ปี' : 'y'}
            </span>
          </div>
          <div style={{ fontSize: 10, color: 'var(--ink-mute)', marginTop: 3, textAlign: 'center' }}>{lang === 'th' ? 'จำนวนปี' : 'Years'}</div>
        </div>

        {/* Months */}
        <div>
          <div style={{ position: 'relative' }}>
            <input type="number" min="0" max="11" value={months || ''}
              onChange={(e) => onChange(Number(years) || 0, Number(e.target.value) || 0)}
              placeholder="0"
              style={{ width: '100%', padding: '9px 38px 9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'var(--font-mono)', textAlign: 'right' }} />
            <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 11, color: 'var(--ink-mute)', pointerEvents: 'none' }}>
              {lang === 'th' ? 'ด' : 'm'}
            </span>
          </div>
          <div style={{ fontSize: 10, color: 'var(--ink-mute)', marginTop: 3, textAlign: 'center' }}>{lang === 'th' ? 'จำนวนเดือน' : 'Months'}</div>
        </div>

        {/* Summary */}
        <div style={{
          padding: '9px 12px',
          background: totalMonths > 0 ? 'var(--syk-blue-tint)' : 'var(--glass-2)',
          border: '1px solid ' + (totalMonths > 0 ? 'rgba(30,58,95,0.3)' : 'var(--line)'),
          borderRadius: 8,
          fontSize: 12, fontFamily: 'var(--font-mono)',
          color: totalMonths > 0 ? 'var(--syk-blue)' : 'var(--ink-mute)',
          fontWeight: 600,
          textAlign: 'center',
        }}>
          {totalMonths > 0
            ? `≈ ${totalMonths} ${lang === 'th' ? 'เดือน' : 'months'}`
            : (lang === 'th' ? 'รวม' : 'Total')}
        </div>
      </div>

      {/* Quick presets */}
      <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
        {presets.map((p, i) => {
          const active = (Number(years) || 0) === p.y && (Number(months) || 0) === p.m;
          return (
            <button key={i} type="button" onClick={() => onChange(p.y, p.m)}
              style={{
                flex: 1, padding: '4px 0',
                background: active ? 'var(--syk-blue-tint)' : 'transparent',
                border: '1px solid ' + (active ? 'var(--syk-blue)' : 'var(--line)'),
                color: active ? 'var(--syk-blue)' : 'var(--ink-mute)',
                borderRadius: 4, cursor: 'pointer', fontSize: 10.5, fontWeight: 500, fontFamily: 'var(--font-mono)',
              }}>{p.label}</button>
          );
        })}
      </div>
    </div>
  );
}

// ─── Date math: add/subtract years (+ optional months) ───────
function addPeriod(iso, years, months = 0) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  const totalMonths = Math.round(years * 12) + (months || 0);
  d.setMonth(d.getMonth() + totalMonths);
  return d.toISOString().split('T')[0];
}
function subtractPeriod(iso, years, months = 0) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  const totalMonths = Math.round(years * 12) + (months || 0);
  d.setMonth(d.getMonth() - totalMonths);
  return d.toISOString().split('T')[0];
}
// Add total months (positive or negative)
function addMonths(iso, totalMonths) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  d.setMonth(d.getMonth() + (totalMonths || 0));
  return d.toISOString().split('T')[0];
}
// Compute exact years+months difference between 2 ISO dates
function monthsBetween(startIso, endIso) {
  if (!startIso || !endIso) return { years: 0, months: 0 };
  const s = new Date(startIso + 'T00:00:00');
  const e = new Date(endIso + 'T00:00:00');
  let months = (e.getFullYear() - s.getFullYear()) * 12 + (e.getMonth() - s.getMonth());
  if (e.getDate() < s.getDate()) months--;
  if (months < 0) months = 0;
  return { years: Math.floor(months / 12), months: months % 12 };
}
function yearsBetween(startIso, endIso) {
  const { years, months } = monthsBetween(startIso, endIso);
  return years + months / 12;
}

// ─── Value field with VAT 7% toggle ─────────────────────────
function ValueWithVAT({ lang, value, vatIncluded, onValueChange, onVatChange }) {
  const v = Number(value) || 0;
  // If vat_included: value IS total (including VAT), pre-VAT = value / 1.07
  // If not included: value is pre-VAT; +VAT = value × 0.07; total = value × 1.07
  const preVat = vatIncluded ? v / 1.07 : v;
  const vatAmt = preVat * 0.07;
  const total  = preVat + vatAmt;
  const fmtTHB2 = (n) => n.toLocaleString('th-TH', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  return (
    <div>
      <div className="micro" style={{ marginBottom: 6 }}>
        {lang === 'th' ? 'มูลค่าโครงการ (บาท) *' : 'Project Value (THB) *'}
      </div>
      <input type="number" value={value || ''} onChange={(e) => onValueChange(e.target.value)}
        placeholder="0"
        style={{ width: '100%', padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit' }} />

      {/* VAT toggle */}
      <label style={{
        display: 'flex', alignItems: 'center', gap: 8, marginTop: 8,
        padding: '7px 10px', background: vatIncluded ? 'var(--syk-blue-tint)' : 'var(--glass-2)',
        border: '1px solid ' + (vatIncluded ? 'rgba(30,58,95,0.25)' : 'var(--line)'),
        borderRadius: 6, cursor: 'pointer', fontSize: 12,
        transition: 'background .12s, border-color .12s',
      }}>
        <input type="checkbox" checked={!!vatIncluded} onChange={(e) => onVatChange(e.target.checked)}
          style={{ accentColor: 'var(--syk-blue)', cursor: 'pointer', width: 14, height: 14 }} />
        <span style={{ color: vatIncluded ? 'var(--syk-blue)' : 'var(--ink-soft)', fontWeight: 500 }}>
          {lang === 'th' ? 'ราคานี้รวม VAT 7% แล้ว' : 'Price includes VAT 7%'}
        </span>
      </label>

      {/* Computed breakdown */}
      {v > 0 && (
        <div style={{ marginTop: 8, padding: '8px 10px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 6, fontSize: 11.5, color: 'var(--ink-soft)', fontFamily: 'var(--font-mono)', lineHeight: 1.7 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span>{lang === 'th' ? 'ก่อน VAT' : 'Pre-VAT'}</span>
            <span>{fmtTHB2(preVat)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span>+ VAT 7%</span>
            <span>{fmtTHB2(vatAmt)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, color: 'var(--ink)', borderTop: '1px dashed var(--line-strong)', paddingTop: 4, marginTop: 2 }}>
            <span>{lang === 'th' ? 'รวมทั้งสิ้น' : 'Total'}</span>
            <span>{fmtTHB2(total)}</span>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Date helpers: ISO ↔ dd/mm/yyyy ─────────────────────────
function isoToDDMMYY(iso) {
  if (!iso) return '';
  const m = String(iso).match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (!m) return iso;
  return `${m[3]}/${m[2]}/${m[1]}`;
}
function ddmmyyToISO(str) {
  if (!str) return '';
  // Accept dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy
  const m = String(str).match(/^(\d{1,2})[\/\-\.](\d{1,2})[\/\-\.](\d{4})$/);
  if (!m) return null;
  return `${m[3]}-${m[2].padStart(2,'0')}-${m[1].padStart(2,'0')}`;
}

function FInp({ label, value, onChange, type = 'text', placeholder = '', disabled = false }) {
  // Custom dd/mm/yyyy date input — locale-independent
  if (type === 'date') return <DateField label={label} value={value} onChange={onChange} disabled={disabled} />;

  return (
    <div>
      <div className="micro" style={{ marginBottom: 6 }}>{label}</div>
      <input type={type} value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} disabled={disabled}
        style={{ width: '100%', padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13, opacity: disabled ? 0.6 : 1, fontFamily: 'inherit' }} />
    </div>
  );
}

function DateField({ label, value, onChange, disabled }) {
  // 2 input strategy: a visible text input (dd/mm/yyyy) + a hidden type=date for the calendar picker
  const [text, setText] = React.useState(isoToDDMMYY(value));
  const [error, setError] = React.useState(false);
  const hiddenRef = React.useRef(null);

  React.useEffect(() => { setText(isoToDDMMYY(value)); }, [value]);

  const handleTextChange = (e) => {
    const v = e.target.value;
    setText(v);
    if (!v) { setError(false); onChange(''); return; }
    const iso = ddmmyyToISO(v);
    if (iso) { setError(false); onChange(iso); }
    else { setError(true); }
  };

  const handlePickerChange = (e) => {
    const iso = e.target.value;
    setText(isoToDDMMYY(iso));
    setError(false);
    onChange(iso);
  };

  return (
    <div>
      <div className="micro" style={{ marginBottom: 6 }}>{label}</div>
      <div style={{ position: 'relative' }}>
        <input type="text" value={text} onChange={handleTextChange}
          placeholder="dd/mm/yyyy" disabled={disabled} maxLength={10}
          style={{
            width: '100%', padding: '9px 38px 9px 12px',
            background: 'var(--glass-2)',
            border: `1px solid ${error ? 'var(--rose)' : 'var(--line)'}`,
            borderRadius: 8, color: 'var(--ink)', fontSize: 13,
            fontFamily: 'var(--font-mono)', letterSpacing: '0.02em',
            opacity: disabled ? 0.6 : 1,
          }} />
        <button type="button" onClick={() => { hiddenRef.current?.showPicker?.(); hiddenRef.current?.click?.(); }}
          disabled={disabled}
          style={{
            position: 'absolute', right: 4, top: '50%', transform: 'translateY(-50%)',
            width: 30, height: 30, border: 0, background: 'transparent',
            cursor: disabled ? 'default' : 'pointer', color: 'var(--ink-mute)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 6,
          }}
          onMouseEnter={(e) => !disabled && (e.currentTarget.style.background = 'var(--glass-3)')}
          onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
          title="เลือกจากปฏิทิน">
          <I.calendar size={15} />
        </button>
        <input ref={hiddenRef} type="date" value={value || ''} onChange={handlePickerChange}
          style={{ position: 'absolute', right: 4, top: '50%', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }} />
      </div>
      {error && <div style={{ fontSize: 10, color: 'var(--rose)', marginTop: 3 }}>รูปแบบ: dd/mm/yyyy เช่น 25/12/2026</div>}
    </div>
  );
}

function FInpSelect({ label, value, onChange, options }) {
  return (
    <div>
      <div className="micro" style={{ marginBottom: 6 }}>{label}</div>
      <select value={value} onChange={(e) => onChange(e.target.value)}
        style={{ width: '100%', padding: '9px 12px', background: 'var(--glass-2)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink)', fontSize: 13 }}>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </div>
  );
}

// ─── Add Record Modal (lightweight forms for BOQ/Contract/Drawing/PR-PO) ──
function AddRecordModal({ type, project, lang, onClose, onSave }) {
  const [form, setForm] = useState(() => defaultRecord(type));
  const toast = useToast();
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = () => {
    onSave(form);
  };

  const config = {
    boqs: { title: lang === 'th' ? 'เพิ่มใบเสนอราคา' : 'Add BOQ', icon: '📄' },
    contracts: { title: lang === 'th' ? 'เพิ่มสัญญา' : 'Add Contract', icon: '📜' },
    drawings: { title: lang === 'th' ? 'เพิ่มแบบก่อสร้าง' : 'Add Drawing', icon: '📐' },
    prpos: { title: lang === 'th' ? 'เพิ่ม PR / PO' : 'Add PR / PO', icon: '🛒' },
  }[type];

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)', zIndex: 1100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div className="card anim-fadein" onClick={(e) => e.stopPropagation()} style={{ width: 'min(580px, 100%)', maxHeight: '90vh', overflowY: 'auto', padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <div>
            <div className="micro">{lang === 'th' ? 'ผูกกับโครงการ' : 'Linked to'}: <strong className="mono">{project.code}</strong></div>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 4 }}>{config.icon} {config.title}</div>
          </div>
          <button className="btn btn-sm btn-ghost" onClick={onClose}><I.x /></button>
        </div>

        {type === 'boqs' && <BOQForm form={form} set={set} lang={lang} />}
        {type === 'contracts' && <ContractForm form={form} set={set} lang={lang} />}
        {type === 'drawings' && <DrawingForm form={form} set={set} lang={lang} />}
        {type === 'prpos' && <PRPOForm form={form} set={set} lang={lang} />}

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <button className="btn" style={{ flex: 1, justifyContent: 'center' }} onClick={onClose}>{lang === 'th' ? 'ยกเลิก' : 'Cancel'}</button>
          <button className="btn btn-primary" style={{ flex: 1, justifyContent: 'center' }} onClick={submit}>
            <I.check /> {lang === 'th' ? 'บันทึก' : 'Save'}
          </button>
        </div>
      </div>
    </div>
  );
}

function defaultRecord(type) {
  const today = new Date().toISOString().split('T')[0];
  if (type === 'boqs') return { title: '', date: today, items_count: 0, total: 0, status: 'draft' };
  if (type === 'contracts') return { party: '', kind: 'Owner-Contractor', value: 0, signed: today, end: '', retention: 0.05 };
  if (type === 'drawings') return { name: '', discipline: 'Architecture', revision: 'A', scale: '1:100', file_name: '' };
  if (type === 'prpos') return { type: 'PR', vendor: '', description: '', date: today, total: 0, status: 'pending' };
  return {};
}

function BOQForm({ form, set, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <div style={{ gridColumn: 'span 2' }}>
        <FInp label={lang === 'th' ? 'ชื่อใบเสนอราคา' : 'BOQ Title'} value={form.title} onChange={(v) => set('title', v)} placeholder={lang === 'th' ? 'เช่น ใบเสนอราคาบ้าน 2 ชั้น' : 'BOQ name'} />
      </div>
      <FInp label={lang === 'th' ? 'วันที่' : 'Date'} type="date" value={form.date} onChange={(v) => set('date', v)} />
      <FInp label={lang === 'th' ? 'จำนวนรายการ' : 'Items count'} type="number" value={form.items_count} onChange={(v) => set('items_count', Number(v))} />
      <FInp label={lang === 'th' ? 'มูลค่ารวม (บาท)' : 'Total (THB)'} type="number" value={form.total} onChange={(v) => set('total', Number(v))} />
      <FInpSelect label="Status" value={form.status} onChange={(v) => set('status', v)}
        options={[
          { value: 'draft', label: lang === 'th' ? 'ร่าง' : 'Draft' },
          { value: 'submitted', label: lang === 'th' ? 'ส่งแล้ว' : 'Submitted' },
          { value: 'approved', label: lang === 'th' ? 'อนุมัติแล้ว' : 'Approved' },
          { value: 'rejected', label: lang === 'th' ? 'ปฏิเสธ' : 'Rejected' },
        ]} />
    </div>
  );
}

function ContractForm({ form, set, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <div style={{ gridColumn: 'span 2' }}>
        <FInp label={lang === 'th' ? 'คู่สัญญา' : 'Counterparty'} value={form.party} onChange={(v) => set('party', v)} placeholder={lang === 'th' ? 'ชื่อ-บริษัท' : 'Name/Company'} />
      </div>
      <FInpSelect label={lang === 'th' ? 'ประเภทสัญญา' : 'Contract type'} value={form.kind} onChange={(v) => set('kind', v)}
        options={[
          { value: 'Owner-Contractor', label: lang === 'th' ? 'เจ้าของ-ผู้รับเหมา' : 'Owner-Contractor' },
          { value: 'Subcontract', label: lang === 'th' ? 'สัญญาช่วง' : 'Subcontract' },
          { value: 'Supply', label: lang === 'th' ? 'จัดซื้อจัดจ้าง' : 'Supply' },
        ]} />
      <FInp label={lang === 'th' ? 'มูลค่า (บาท)' : 'Value (THB)'} type="number" value={form.value} onChange={(v) => set('value', Number(v))} />
      <FInp label={lang === 'th' ? 'วันเซ็นสัญญา' : 'Signed date'} type="date" value={form.signed} onChange={(v) => set('signed', v)} />
      <FInp label={lang === 'th' ? 'วันสิ้นสุดสัญญา' : 'End date'} type="date" value={form.end} onChange={(v) => set('end', v)} />
      <div style={{ gridColumn: 'span 2' }}>
        <FInp label={lang === 'th' ? 'เงินประกัน (สัดส่วน เช่น 0.05 = 5%)' : 'Retention (e.g. 0.05 = 5%)'} type="number" value={form.retention} onChange={(v) => set('retention', Number(v))} />
      </div>
    </div>
  );
}

function DrawingForm({ form, set, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <div style={{ gridColumn: 'span 2' }}>
        <FInp label={lang === 'th' ? 'ชื่อแบบ' : 'Drawing name'} value={form.name} onChange={(v) => set('name', v)} placeholder={lang === 'th' ? 'เช่น แปลนสถาปัตยกรรม ชั้น 1' : 'e.g. Floor plan'} />
      </div>
      <FInpSelect label={lang === 'th' ? 'หมวด' : 'Discipline'} value={form.discipline} onChange={(v) => set('discipline', v)}
        options={[
          { value: 'Architecture', label: lang === 'th' ? 'สถาปัตยกรรม' : 'Architecture' },
          { value: 'Structure', label: lang === 'th' ? 'โครงสร้าง' : 'Structure' },
          { value: 'Electrical', label: lang === 'th' ? 'ไฟฟ้า' : 'Electrical' },
          { value: 'Plumbing', label: lang === 'th' ? 'ประปา-สุขาภิบาล' : 'Plumbing' },
          { value: 'MEP', label: 'MEP' },
        ]} />
      <FInp label={lang === 'th' ? 'รหัสรีวิชั่น' : 'Revision'} value={form.revision} onChange={(v) => set('revision', v)} placeholder="A / B / C" />
      <FInp label={lang === 'th' ? 'สเกล' : 'Scale'} value={form.scale} onChange={(v) => set('scale', v)} placeholder="1:100" />
      <FInp label={lang === 'th' ? 'ชื่อไฟล์' : 'File name'} value={form.file_name} onChange={(v) => set('file_name', v)} placeholder="DWG-001.pdf" />
    </div>
  );
}

function PRPOForm({ form, set, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <FInpSelect label={lang === 'th' ? 'ประเภท' : 'Type'} value={form.type} onChange={(v) => set('type', v)}
        options={[
          { value: 'PR', label: 'PR (Purchase Request)' },
          { value: 'PO', label: 'PO (Purchase Order)' },
        ]} />
      <FInp label={lang === 'th' ? 'วันที่' : 'Date'} type="date" value={form.date} onChange={(v) => set('date', v)} />
      <div style={{ gridColumn: 'span 2' }}>
        <FInp label={lang === 'th' ? 'ผู้ขาย / Vendor' : 'Vendor'} value={form.vendor} onChange={(v) => set('vendor', v)} placeholder="SCG / TSC / ..." />
      </div>
      <div style={{ gridColumn: 'span 2' }}>
        <FInp label={lang === 'th' ? 'รายละเอียด' : 'Description'} value={form.description} onChange={(v) => set('description', v)} placeholder={lang === 'th' ? 'รายละเอียดสินค้า/บริการ' : 'Description'} />
      </div>
      <FInp label={lang === 'th' ? 'มูลค่ารวม (บาท)' : 'Total (THB)'} type="number" value={form.total} onChange={(v) => set('total', Number(v))} />
      <FInpSelect label="Status" value={form.status} onChange={(v) => set('status', v)}
        options={[
          { value: 'pending', label: lang === 'th' ? 'รออนุมัติ' : 'Pending' },
          { value: 'approved', label: lang === 'th' ? 'อนุมัติแล้ว' : 'Approved' },
          { value: 'sent', label: lang === 'th' ? 'ส่งให้ vendor' : 'Sent' },
          { value: 'received', label: lang === 'th' ? 'รับของแล้ว' : 'Received' },
        ]} />
    </div>
  );
}

// ─── Sample Data Seeder ─────────────────────────────────────
function seedSampleData() {
  const samples = [
    {
      project_type: 'HSE',
      name: 'บ้านพักอาศัย 2 ชั้น คุณวิชัย', client: 'คุณวิชัย ตั้งสกุล',
      site: 'ลาดพร้าว 71', value: 4_850_000, vat_included: true, phase: 'construction',
      contract_signed: '2025-08-01', handover_date: '2026-02-01', duration_years: 0, duration_months: 6,
      warranty_years: 1, warranty_months: 0,
      notes: 'บ้านโครงสร้าง ค.ส.ล. หลังคากระเบื้องลอนคู่',
    },
    {
      project_type: 'FAC',
      name: 'ต่อเติมโรงงาน บ.รุ่งเรืองพลาส', client: 'บ.รุ่งเรืองพลาส จำกัด',
      site: 'บางบอน กรุงเทพฯ', value: 8_200_000, vat_included: false, phase: 'construction',
      contract_signed: '2025-08-28', handover_date: '2026-04-28', duration_years: 0, duration_months: 8,
      warranty_years: 2, warranty_months: 0,
      notes: 'ต่อเติมส่วนผลิตและคลังสินค้า พื้นที่ 1,200 ตร.ม.',
    },
    {
      project_type: 'COM',
      name: 'อาคารพาณิชย์ 3 ชั้น คุณสมเกียรติ', client: 'คุณสมเกียรติ พงษ์พานิช',
      site: 'บางนา-ตราด กม.5', value: 12_500_000, vat_included: true, phase: 'quotation',
      contract_signed: '2026-05-18', handover_date: '2027-05-18', duration_years: 1, duration_months: 0,
      warranty_years: 2, warranty_months: 0,
      notes: 'รอลูกค้าตัดสินใจ ส่งใบเสนอราคาแล้ว 18 พ.ค. 2569',
    },
  ];
  samples.forEach((data, i) => {
    try {
      const p = window.ProjectManager.create(data);
      // Add some sample records to first project
      if (i === 0) {
        window.ProjectManager.addRecord(p.code, 'boqs', {
          title: 'ใบเสนอราคาหลัก v.2', date: '2025-07-25', items_count: 142, total: 4_850_000, status: 'approved',
        });
        window.ProjectManager.addRecord(p.code, 'contracts', {
          party: data.client, kind: 'Owner-Contractor', value: 4_850_000, signed: '2025-08-01', end: '2026-02-28', retention: 0.05,
        });
        window.ProjectManager.addRecord(p.code, 'drawings', {
          name: 'แปลนสถาปัตยกรรม ชั้น 1-2', discipline: 'Architecture', revision: 'B', scale: '1:100', file_name: 'DWG-001-A.pdf',
        });
        window.ProjectManager.addRecord(p.code, 'drawings', {
          name: 'ฐานราก & เสาเข็ม', discipline: 'Structure', revision: 'A', scale: '1:75', file_name: 'DWG-002-S.pdf',
        });
        window.ProjectManager.addRecord(p.code, 'prpos', {
          type: 'PR', vendor: 'SCG', description: 'ปูนซีเมนต์ + เหล็กเส้น', date: '2025-11-15', total: 72_400, status: 'approved',
        });
        window.ProjectManager.addRecord(p.code, 'prpos', {
          type: 'PO', vendor: 'TSC', description: 'เหล็กข้ออ้อย DB12 200 เส้น', date: '2025-11-16', total: 57_000, status: 'sent',
        });
      }
    } catch {}
  });
}

window.ProjectOverviewPage = ProjectOverviewPage;
