// vkaff-shell.jsx - shared building blocks + cover/toc/sidebar/topbar/footer/annex
// Exposes components on window for vkaff-sections.jsx and vkaff-app.jsx to use.

const { useState, useEffect } = React;

// DOCUMENT CONTROL
const DOC = {
  version: "2.2.3",
  effective: "25 May 2026",
  nextReview: "25 May 2027",
  owner: "People Operations",
};

// CHAPTER STRUCTURE / NAVIGATION
const VK_CHAPTERS = [
  { id: "cover",        num: "·",   title: "Cover",                                       short: "Cover" },
  { id: "contents",     num: "·",   title: "Contents",                                    short: "Contents" },
  // Introduction
  { id: "s1",  num: "01", title: "About This Handbook",                          short: "About",                  group: "Introduction" },
  { id: "s2",  num: "02", title: "Who We Are",                                   short: "Who We Are",             group: "Introduction" },
  { id: "s3",  num: "03", title: "Workplace Conduct",                            short: "Workplace",              group: "Introduction" },
  // Employment
  { id: "s4",  num: "04", title: "Employment Practices",                         short: "Employment",             group: "Employment" },
  { id: "s5",  num: "05", title: "Compensation",                                 short: "Compensation",           group: "Employment" },
  { id: "s6",  num: "06", title: "Benefits",                                     short: "Benefits",               group: "Employment" },
  { id: "s7",  num: "07", title: "Leave Entitlements",                           short: "Leave",                  group: "Employment" },
  { id: "s8",  num: "08", title: "Travel and Expenses",                          short: "Travel",                 group: "Employment" },
  // Conduct
  { id: "s9",  num: "09", title: "Code of Conduct",                              short: "Conduct",                group: "Conduct" },
  { id: "s10", num: "10", title: "Anti-Bribery, Gifts and Corruption",           short: "Anti-Bribery",           group: "Conduct" },
  { id: "s11", num: "11", title: "Conflict of Interest",                         short: "Conflict of Interest",   group: "Conduct" },
  // Data, IP & systems
  { id: "s12", num: "12", title: "Confidentiality and Intellectual Property",    short: "Confidentiality & IP",   group: "Data & Systems" },
  { id: "s13", num: "13", title: "Personal Data Protection",                     short: "PDPA",                   group: "Data & Systems" },
  { id: "s14", num: "14", title: "IT, AI and Company Property",                  short: "IT, AI & Property",      group: "Data & Systems" },
  // Workplace
  { id: "s15", num: "15", title: "Workplace Safety and Health",                  short: "Safety & Health",        group: "Workplace" },
  { id: "s16", num: "16", title: "Workplace Fairness and Anti-Harassment",       short: "Fairness",               group: "Workplace" },
  // Process
  { id: "s17", num: "17", title: "Disciplinary, Grievance and Whistleblowing",   short: "Disciplinary",           group: "Process" },
  { id: "s18", num: "18", title: "Termination and Retirement",                   short: "Departure",              group: "Process" },
  // Annex
  { id: "annex", num: "·", title: "Annex",                                       short: "Annex",                  group: "Annex" },
];

// REUSABLE PIECES

function ChapterHead({ num, kicker, title, lede }) {
  return (
    <div className="ch-head">
      <div className="ch-head__row">
        <span className="ch-head__chip">SECTION {num}</span>
        <span>{kicker}</span>
      </div>
      <h2 className="ch-head__title" dangerouslySetInnerHTML={{__html: title}} />
      {lede && <p className="ch-head__lede">{lede}</p>}
    </div>
  );
}

function Sub({ num, title, children }) {
  return (
    <div className="sub">
      <div className="sub__head">
        <span className="sub__num">{num}</span>
        <h3 className="sub__title">{title}</h3>
      </div>
      {children}
    </div>
  );
}

function P({ children, lede }) {
  return <p className={lede ? "lede" : ""}>{children}</p>;
}

function Bullets({ items, ordered }) {
  const Tag = ordered ? "ol" : "ul";
  return (
    <Tag className="bullets">
      {items.map((it, i) => <li key={i} dangerouslySetInnerHTML={{__html: it}} />)}
    </Tag>
  );
}

function Callout({ label, children, icon = "§", light }) {
  return (
    <div className={"callout" + (light ? " light" : "")}>
      <div className="callout__icon">{icon}</div>
      <div>
        {label && <div className="callout__label">{label}</div>}
        <p className="callout__body">{children}</p>
      </div>
    </div>
  );
}

function DataList({ rows }) {
  return (
    <div className="data">
      {rows.map((r, i) => (
        <div key={i} className="data__row">
          <div className="data__k">{r.k}</div>
          <div className="data__v">
            <span dangerouslySetInnerHTML={{__html: r.v}} />
            {r.s && <small dangerouslySetInnerHTML={{__html: r.s}} />}
          </div>
          {r.t && <div className={"tag" + (r.tone ? " " + r.tone : "")}>{r.t}</div>}
        </div>
      ))}
    </div>
  );
}

function Cards({ items, cols = 2 }) {
  return (
    <div className={"cards" + (cols === 3 ? " cards--3" : "")}>
      {items.map((c, i) => (
        <div key={i} className={"card" + (c.dark ? " dark" : "")}>
          {c.num && <div className="card__num">{c.num}</div>}
          <h4 className="card__title">{c.title}</h4>
          <p className="card__body" dangerouslySetInnerHTML={{__html: c.body}} />
        </div>
      ))}
    </div>
  );
}

function Priority({ items }) {
  return (
    <div className="priority">
      {items.map((it, i) => (
        <div key={i} className="priority__item">
          <div className="priority__num">{i+1}</div>
          <div>{it}</div>
          <div className="tag">{i === 0 ? "Highest priority" : i === items.length - 1 ? "Default" : "Above"}</div>
        </div>
      ))}
    </div>
  );
}

// COVER

function Cover() {
  return (
    <section id="cover" className="cover" data-screen-label="00 Cover">
      <div className="cover__top">
        <div className="cover__brand">
          <img src="/handbook/assets/aff-logo.png" alt="AFF" />
          <div className="cover__brand-text">
            <b>Advanced Flavors &amp; Fragrances</b>
            <span>Pte. Ltd. · Singapore</span>
          </div>
        </div>
        <div className="meta">
          <span>Version<b>{DOC.version}</b></span>
          <span>Effective<b>{DOC.effective}</b></span>
          <span>Pages<b>18 + Annex</b></span>
        </div>
      </div>

      <div className="cover__middle">
        <div className="cover__eyebrow">
          <b>The VKAFF Handbook</b>
          <span style={{color:"var(--muted-2)"}}>·</span>
          <span>Issued to all employees</span>
        </div>
        <h1 className="cover__title">
          Employee<br/>
          <span className="grey">Handbook.</span>
        </h1>
        <div className="cover__promise">
          <span className="dot"></span>
          <span><b>Always Advancing.</b> &nbsp;· Our brand promise.</span>
        </div>
        <p className="cover__sub">
          At VKAFF, we make flavours that bring food and drink to life. This Handbook sets out the policies and standards of conduct that apply to every employee of Advanced Flavors &amp; Fragrances Pte. Ltd. Read it, follow it, and use good judgement in everything you do.
        </p>
      </div>

      <div className="cover__bottom">
        <div className="cell">
          <div className="lbl">Version</div>
          <div className="val">{DOC.version}</div>
        </div>
        <div className="cell">
          <div className="lbl">Effective from</div>
          <div className="val">{DOC.effective}</div>
        </div>
        <div className="cell">
          <div className="lbl">Owner · Next review</div>
          <div className="val">{DOC.owner} · {DOC.nextReview}</div>
        </div>
        <div className="cell dark">
          <div className="lbl">Classification</div>
          <div className="val">Internal, issued to all employees</div>
        </div>
      </div>
    </section>
  );
}

// TABLE OF CONTENTS

function Contents({ onJump }) {
  const sections = VK_CHAPTERS.filter(c => c.group);
  const groups = [];
  sections.forEach(c => {
    let g = groups.find(x => x.name === c.group);
    if (!g) { g = { name: c.group, items: [] }; groups.push(g); }
    g.items.push(c);
  });

  return (
    <section id="contents" className="chapter" data-screen-label="00 Contents" style={{paddingTop: 96}}>
      <ChapterHead
        num="00"
        kicker="Table of Contents"
        title="Contents."
        lede="Eighteen sections plus the Annex. Defined terms are listed in A.3. Refer to the section index below."
      />
      <div className="container container--wide">
        <div className="toc">
          {groups.map((g) => (
            <React.Fragment key={g.name}>
              <div className="toc__group-head">{g.name}</div>
              {g.items.map((c) => (
                <div key={c.id} className="toc__item" onClick={() => onJump(c.id)}>
                  <div className="toc__num">{c.num === "·" ? "·" : c.num}</div>
                  <div className="toc__name">{c.title}</div>
                  <div className="toc__pages">P. {String((parseInt(c.num)||0)*2 + 4).padStart(2,"0")}</div>
                  <div className="toc__arrow">→</div>
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

// ANNEX

function Annex() {
  const glossary = [
    { term: "AWS", def: "Annual Wage Supplement (sometimes called 13th-month). Contractual where stated in your employment contract, otherwise discretionary." },
    { term: "CDCSA", def: "Child Development Co-Savings Act. Governs Singapore's Government-Paid Maternity, Paternity, Adoption, Childcare, and Shared Parental Leave schemes." },
    { term: "CPF", def: "Central Provident Fund. Singapore's social-security savings scheme; mandatory employer and employee contributions for Singapore Citizens and Permanent Residents." },
    { term: "DPO", def: "Data Protection Officer. The role designated under PDPA section 11 to oversee personal-data compliance. Contact via your HR representative." },
    { term: "EA", def: "Employment Act (Singapore). The principal statute governing employment terms." },
    { term: "ECT", def: "Employment Claims Tribunal. Forum for resolving statutory salary-related and wrongful-dismissal claims, accessed after TADM mediation." },
    { term: "EFMA", def: "Employment of Foreign Manpower Act. Governs Work Permit, S Pass, and Employment Pass holders." },
    { term: "GMP", def: "Good Manufacturing Practice. Standards governing hygiene, contamination control, and traceability in food and flavour production." },
    { term: "GPCL / GPML", def: "Government-Paid Childcare Leave / Government-Paid Maternity Leave under the CDCSA." },
    { term: "Hari Raya Puasa / Haji", def: "Singapore public holidays marking the end of Ramadan (Puasa) and the Hajj season (Haji)." },
    { term: "IRAS", def: "Inland Revenue Authority of Singapore. Tax authority; processes Form IR21 tax clearance for departing foreign employees." },
    { term: "KET", def: "Key Employment Terms. Mandatory written summary of terms, issued separately under EA section 95A within 14 days of starting." },
    { term: "MC", def: "Medical certificate. Required to claim paid outpatient sick leave beyond the self-certification allowance." },
    { term: "MINDEF", def: "Ministry of Defence. Administers National Service and reservist obligations." },
    { term: "MOM", def: "Ministry of Manpower. Singapore's employment and workplace-safety regulator." },
    { term: "MSF", def: "Ministry of Social and Family Development. Administers parental-leave schemes under the CDCSA." },
    { term: "NS", def: "National Service. Singapore's compulsory military service obligation, including reservist in-camp training." },
    { term: "PCA", def: "Prevention of Corruption Act. Governs anti-bribery offences in Singapore." },
    { term: "PDPA", def: "Personal Data Protection Act 2012. Governs collection, use, disclosure, and protection of personal data." },
    { term: "PPE", def: "Personal Protective Equipment." },
    { term: "SDL", def: "Skills Development Levy. Employer contribution that funds the Skills Development Fund supporting workforce training." },
    { term: "SPL", def: "Shared Parental Leave. A pool of leave shared between parents on top of maternity and paternity leave, under the CDCSA." },
    { term: "TADM", def: "Tripartite Alliance for Dispute Management. Mediation service for employment-related disputes; precedes a claim to the ECT." },
    { term: "TAFEP", def: "Tripartite Alliance for Fair and Progressive Employment Practices. Promotes fair workplaces and handles fair-employment complaints." },
    { term: "Vesak Day", def: "Singapore public holiday marking the birth, enlightenment, and passing of the Buddha." },
    { term: "WFA", def: "Workplace Fairness Act 2024. Codifies protections against discrimination on listed protected characteristics." },
    { term: "WSH Act", def: "Workplace Safety and Health Act 2006. Sets duties for safe workplaces and the right to stop unsafe work." },
  ];

  const contacts = [
    { who: "Day-to-day People matters, leave, claims, payslip queries", route: "Your manager, escalating to HR" },
    { who: "PDPA requests and data-breach reports", route: "HR (routes to the Data Protection Officer)" },
    { who: "Grievance escalation beyond manager and HR", route: "The CEO" },
    { who: "Whistleblowing on fraud, corruption, safety, or other serious wrongdoing", route: "The Group CEO directly" },
    { who: "Workplace fairness or harassment concerns", route: "Your manager, the next level up if it involves your manager, then the CEO" },
    { who: "Safety incidents and near misses", route: "Your supervisor immediately; HR notified" },
  ];

  return (
    <section id="annex" className="chapter" data-screen-label="Annex">
      <ChapterHead
        num="A"
        kicker="Annex"
        title='Acknowledgement, <span class="grey">glossary, contacts.</span>'
        lede="Reference material that supports the main chapters."
      />
      <div className="container prose">

        <Sub num="A.1" title="Acknowledgement of Receipt">
          <P>
            I confirm that I have received, read, and understood the VKAFF Employee Handbook. I understand that it forms part of my terms of employment, that I am required to comply with it and with any updates communicated to me, and that the Company may revise, amend, or withdraw any part of it as business needs or regulations change.
          </P>
          <P>
            I understand that this Handbook does not by itself create a contract of employment beyond my employment agreement, and that where any conflict arises, my employment agreement takes priority, followed by the policies incorporated by reference, then this Handbook. For employees based outside Singapore, I understand that the mandatory law of the country where I work prevails over this Handbook and my employment agreement on the categories where local law sets a minimum.
          </P>

          <div className="form">
            <h3>Acknowledgement</h3>
            <p>To be completed by the employee and returned to People Operations.</p>
            <div className="form__row">
              <div className="form__field">
                <span className="lbl">Employee Name</span>
                <input type="text" placeholder=" " />
              </div>
              <div className="form__field">
                <span className="lbl">Employee ID</span>
                <input type="text" placeholder=" " />
              </div>
            </div>
            <div className="form__row">
              <div className="form__field signature">
                <span className="lbl">Signature</span>
                <input type="text" placeholder=" " />
              </div>
              <div className="form__field">
                <span className="lbl">Date</span>
                <input type="text" placeholder="DD / MM / YYYY" />
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <span className="lbl">HR Countersignature</span>
                <input type="text" placeholder=" " />
              </div>
              <div className="form__field">
                <span className="lbl">Date received by HR</span>
                <input type="text" placeholder="DD / MM / YYYY" />
              </div>
            </div>
          </div>
        </Sub>

        <Sub num="A.2" title="Glossary">
          <P>Terms and abbreviations used in this Handbook.</P>
          <DataList rows={glossary.map(g => ({ k: g.term, v: g.def }))} />
        </Sub>

        <Sub num="A.3" title="Who to Contact for What">
          <DataList rows={contacts.map(c => ({ k: c.who, v: c.route }))} />
        </Sub>

      </div>
    </section>
  );
}

// SIDEBAR

function Sidebar({ activeId, onJump }) {
  // group nav by group field
  const items = VK_CHAPTERS;
  const grouped = [];
  items.forEach(c => {
    if (!c.group) {
      grouped.push({ kind: "item", item: c });
    } else {
      const lastGroup = grouped.filter(g => g.kind === "group").pop();
      if (!lastGroup || lastGroup.name !== c.group) {
        grouped.push({ kind: "group", name: c.group, items: [c] });
      } else {
        lastGroup.items.push(c);
      }
    }
  });

  return (
    <aside className="sidebar">
      <div className="sidebar__brand">
        <img src="/handbook/assets/aff-logo.png" alt="AFF" />
        <div className="sidebar__brand-meta">
          <b>VKAFF Handbook</b>
          <span>v{DOC.version} · {DOC.effective}</span>
        </div>
      </div>
      <nav className="nav">
        {grouped.map((g, i) => {
          if (g.kind === "item") {
            return (
              <button
                key={g.item.id}
                className={"nav__item cover " + (activeId === g.item.id ? "active" : "")}
                onClick={() => onJump(g.item.id)}
              >
                <span className="nav__num">{g.item.num === "·" ? "•" : g.item.num}</span>
                <span>{g.item.short}</span>
              </button>
            );
          }
          return (
            <div key={"g" + i} className="nav__group">
              <div className="nav__group-label">{g.name}</div>
              {g.items.map(c => (
                <button
                  key={c.id}
                  className={"nav__item " + (activeId === c.id ? "active" : "")}
                  onClick={() => onJump(c.id)}
                >
                  <span className="nav__num">{c.num === "·" ? "•" : c.num}</span>
                  <span>{c.short}</span>
                </button>
              ))}
            </div>
          );
        })}
      </nav>
      <div className="sidebar__foot">
        <span className="lbl">People Ops</span>
        <button onClick={() => window.print()}>
          <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 4V2h8v2M4 11H2V6h12v5h-2M4 9h8v5H4V9z" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Print
        </button>
      </div>
    </aside>
  );
}

function Topbar({ activeId, progress }) {
  const active = VK_CHAPTERS.find(c => c.id === activeId) || VK_CHAPTERS[0];
  return (
    <div className="topbar">
      <div className="topbar__crumb">
        <span><b>VKAFF</b></span>
        <span className="sep">/</span>
        <span>Handbook v{DOC.version}</span>
        <span className="sep">/</span>
        <span><b>{active.num !== "·" ? active.num + " · " : ""}{active.short}</b></span>
      </div>
      <div className="topbar__meta">
        <span className="topbar__progress">{String(Math.round(progress*100)).padStart(2,"0")}%</span>
        <span><span className="dot"></span>Active · v{DOC.version}</span>
      </div>
    </div>
  );
}

// FOOTER

function Footer() {
  return (
    <footer className="footer">
      <div>
        <div className="footer__brand">Advanced Flavors &amp; Fragrances Pte. Ltd.</div>
        <p style={{color:"var(--muted)", fontSize:13, maxWidth:360, lineHeight:1.55, margin:0}}>
          Always Advancing. The promise we make to our customers and to each other.
        </p>
      </div>
      <div className="footer__col">
        <h5>Handbook</h5>
        <a href="#cover">Cover</a>
        <a href="#contents">Contents</a>
        <a href="#annex">Annex</a>
      </div>
      <div className="footer__col">
        <h5>Speak Up</h5>
        <a href="#s17">Grievance Process</a>
        <a href="#s17">Whistleblowing</a>
        <a href="#s16">Anti-Harassment</a>
      </div>
      <div className="footer__col">
        <h5>Document</h5>
        <p style={{color:"var(--muted)", fontSize:12.5, fontFamily:"var(--mono)", textTransform:"uppercase", letterSpacing:"0.08em"}}>
          v{DOC.version}<br/>
          Owner: {DOC.owner}<br/>
          Next review: {DOC.nextReview}<br/>
          © VKAFF 2026
        </p>
      </div>
      <div className="footer__bottom">
        <span>Internal · issued to all employees of VKAFF Singapore</span>
        <span>Effective · {DOC.effective}</span>
      </div>
    </footer>
  );
}

// Expose to other scripts
Object.assign(window, {
  VK_CHAPTERS, DOC,
  ChapterHead, Sub, P, Bullets, Callout, DataList, Cards, Priority,
  Cover, Contents, Annex, Sidebar, Topbar, Footer,
});
