// ProjectGuard — ใช้ wrap หน้า BOQ/Contracts/PR-PO/Drawings
// บล็อกการเข้าใช้ถ้าไม่มี project ที่สร้างผ่าน ProjectManager
// แสดง CTA "ไปสร้างโครงการ" → กระโดดไปหน้า Project Overview

window.ProjectGuard = function ProjectGuard({ children, lang, pageName }) {
  const [count, setCount] = React.useState(() => (window.ProjectManager?.list() || []).length);

  React.useEffect(() => {
    if (!window.ProjectManager) return;
    const unsub = window.ProjectManager.subscribe(list => setCount(list.length));
    return unsub;
  }, []);

  if (count > 0) return children;

  return (
    <div className="anim-fadein">
      <div className="card" style={{ textAlign: 'center', padding: '60px 20px', maxWidth: 640, margin: '40px auto' }}>
        <div style={{ fontSize: 64, marginBottom: 16 }}>🚫</div>
        <h2 style={{ margin: '0 0 8px', fontSize: 20, fontWeight: 700 }}>
          {lang === 'th'
            ? `ยังไม่สามารถใช้งานหน้า "${pageName}" ได้`
            : `Cannot use "${pageName}" yet`}
        </h2>
        <p style={{ color: 'var(--ink-soft)', fontSize: 13, maxWidth: 480, margin: '0 auto 20px', lineHeight: 1.7 }}>
          {lang === 'th'
            ? <>
                หน้านี้ต้องการเลือกโครงการก่อน — แต่ตอนนี้ <strong>ยังไม่มีโครงการในระบบ</strong>
                <br/><br/>
                กรุณาไปที่หน้า <strong style={{ color: 'var(--syk-blue-soft)' }}>"ภาพรวมโครงการ"</strong> เพื่อสร้างโครงการก่อนใช้งาน
              </>
            : <>
                This page requires a project to be selected, but <strong>no projects exist yet</strong>.
                <br/><br/>
                Please go to <strong style={{ color: 'var(--syk-blue-soft)' }}>"Project Overview"</strong> to create one first.
              </>}
        </p>
        <button className="btn btn-primary" onClick={() => window.__appNav?.('overview')} style={{ fontSize: 14, padding: '12px 24px' }}>
          <I.tag /> {lang === 'th' ? 'ไปสร้างโครงการ' : 'Create a project'}
        </button>
      </div>
    </div>
  );
};
