/* ============================================================
   org-chart.jsx — in-app Org Chart for the Leadership Board.
   Mirrors the Google-Slides chart but in the project's look:
   Ownership → Operations → Departments (each with a source person)
   → team members. Office toggle for NWDC / BCDC.
   ============================================================ */
const { useState: useOCState } = React;

/* members of a department within an office */
function membersOf(deptId, office) {
  return PEOPLE.filter((p) =>
    (p.dept === deptId || (deptId === "providers" && p.practices)) &&
    (p.office === office || p.office === "both" || (!p.office && office === "nwdc"))
  );
}

function OfficeLogos({ view }) {
  const set = view === "bcdc"
    ? [["bdc", "Briarcliff Dental Care"]]
    : view === "acg"
    ? [["nwdc", "NWDC"], ["bdc", "BCDC"], ["nwdlab", "NWD Lab"]]
    : [["nwdc", "Northern Westchester Dental Care"], ["nwdlab", "Northern Westchester Dental Lab"]];
  return (
    <div className="oc-head-logos">
      {set.map(([k, alt]) => <img key={k} src={`assets/${k}.png`} alt={alt} />)}
    </div>
  );
}

function PersonChip({ id, label, tone }) {
  const p = personById(id);
  return (
    <div className={"oc-person" + (tone ? " " + tone : "")}>
      <Avatar id={id} size="lg" />
      <div className="ocp-meta">
        <div className="ocp-name">{p.name}</div>
        <div className="ocp-role">{label || p.role}</div>
      </div>
    </div>
  );
}

function DeptNode({ deptId, office }) {
  const d = DEPARTMENTS[deptId];
  const cfg = OFFICES[office];
  const srcId = cfg.sources[deptId];
  const src = srcId ? personById(srcId) : null;
  const members = membersOf(deptId, office).filter((m) => m.id !== srcId);
  const hue = d.hue;
  return (
    <div className="oc-dept" style={{ "--dh": `oklch(0.6 0.12 ${hue})` }}>
      <div className="ocd-head">
        <span className="ocd-name">{d.label}</span>
        <span className="ocd-tags">
          {d.shared && <span className="ocd-flag shared">Shared</span>}
          {d.remote && <span className="ocd-flag remote">Remote</span>}
        </span>
      </div>
      {src ? (
        <div className="ocd-source">
          <Avatar id={src.id} />
          <div className="ocd-src-meta">
            <div className="ocd-src-name">{src.name}</div>
            <div className="ocd-src-label">Source person</div>
          </div>
        </div>
      ) : (
        <div className="ocd-source empty">Source TBD</div>
      )}
      {members.length > 0 && (
        <div className="ocd-members">
          {members.map((m) => (
            <span key={m.id} className="ocd-member" title={m.role}>
              <Avatar id={m.id} size="sm" />
              <span className="ocdm-name">{m.first}{m.remote ? " · remote" : ""}{m.out ? " · out" : ""}</span>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- ACG corporate tree (clickable nodes → popup) ---------- */
function AcgNode({ node, onClick, open }) {
  return (
    <button className={"acg-node" + (open ? " open" : "")} style={{ "--nh": `oklch(0.6 0.12 ${node.hue})` }} onClick={onClick}>
      <span className="acg-node-kind">{node.kind || "Shared service"}</span>
      <span className="acg-node-name">{node.name}</span>
      <span className="acg-node-foot">
        <span className="acg-node-count">{node.count} {node.count === 1 ? "person" : "people"}</span>
        <span className="acg-node-open">View<Icon name="chevron" size={11} /></span>
      </span>
    </button>
  );
}

function AcgPopup({ data, onClose, onJump }) {
  if (!data) return null;
  return (
    <div className="oc-modal-scrim" onClick={onClose}>
      <div className="oc-modal" style={{ "--nh": `oklch(0.6 0.12 ${data.hue})` }} onClick={(e) => e.stopPropagation()}>
        <div className="oc-modal-head">
          <div>
            <div className="oc-modal-kind">{data.kind || "Shared service"}</div>
            <h3>{data.name}</h3>
          </div>
          <button className="oc-modal-x" onClick={onClose}><Icon name="close" size={16} /></button>
        </div>
        <div className="oc-modal-body">
          {data.groups.map((g, i) => (
            <div className="oc-modal-group" key={i}>
              {g.label && <div className="oc-modal-glabel">{g.label}</div>}
              {g.people.map((pid) => {
                const p = personById(pid);
                return (
                  <div className="oc-modal-person" key={pid + i}>
                    <Avatar id={pid} />
                    <div>
                      <div className="omp-name">{p.name}</div>
                      <div className="omp-role">{p.role}{p.note ? ` · ${p.note}` : ""}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        {data.office && (
          <button className="oc-modal-jump" onClick={() => onJump(data.office)}>
            Open the {data.short} chart<Icon name="chevron" size={14} />
          </button>
        )}
      </div>
    </div>
  );
}

function AcgTree({ onJump }) {
  const [popup, setPopup] = useOCState(null);

  const practiceData = (pr) => {
    const cfg = OFFICES[pr.office];
    if (pr.dept) {
      const lead = cfg.sources.lab;
      const members = membersOf("lab", pr.office).filter((m) => m.id !== lead);
      return { name: pr.name, kind: pr.kind, short: pr.short, office: null, hue: pr.hue,
        groups: [{ label: "Lead", people: [lead] }, members.length ? { label: "Team", people: members.map((m) => m.id) } : null].filter(Boolean) };
    }
    const groups = cfg.departments.map((deptId) => {
      const src = cfg.sources[deptId];
      const mem = membersOf(deptId, pr.office).filter((m) => m.id !== src);
      return { label: DEPARTMENTS[deptId].label, people: [src, ...mem.map((m) => m.id)].filter(Boolean) };
    });
    return { name: pr.name, kind: pr.kind, short: pr.short, office: pr.office, hue: pr.hue, groups };
  };
  const sharedData = (s) => ({
    name: s.name, kind: "Shared service", hue: s.hue, office: null,
    groups: [{ label: "Lead", people: [s.lead] }, s.members.length ? { label: "Team", people: s.members } : null].filter(Boolean),
  });

  const practiceCount = (pr) => {
    const cfg = OFFICES[pr.office];
    if (pr.dept) return membersOf("lab", pr.office).length;
    const ids = new Set();
    cfg.departments.forEach((d) => { if (cfg.sources[d]) ids.add(cfg.sources[d]); membersOf(d, pr.office).forEach((m) => ids.add(m.id)); });
    return ids.size;
  };
  const sharedCount = (s) => 1 + s.members.length;

  return (
    <div className="acg-tree">
      <div className="oc-hero">
        <div className="oc-hero-text">
          <span className="eyebrow">Corporate</span>
          <h2>{ACG.label}</h2>
          <p>The umbrella over both practices. Click any box to see who's inside.</p>
        </div>
      </div>

      <div className="oc-tier-label">Ownership</div>
      <div className="oc-row owners">
        {ACG.owners.map((o) => <PersonChip key={o.id} id={o.id} label={o.scope} tone="own" />)}
      </div>
      <div className="oc-stem" />

      <div className="oc-tier-label">Operations</div>
      <div className="oc-row">
        <PersonChip id={ACG.ops} label="Operations Manager · shared across ACG" tone="ops" />
      </div>
      <div className="oc-stem" />

      <div className="oc-tier-label">Practices &amp; Lab</div>
      <div className="oc-bus" />
      <div className="acg-grid practices">
        {ACG.practices.map((pr) => (
          <AcgNode key={pr.id} node={{ ...pr, count: practiceCount(pr) }} open={popup && popup.id === pr.id}
            onClick={() => setPopup({ id: pr.id, ...practiceData(pr) })} />
        ))}
      </div>

      <div className="oc-tier-label" style={{ marginTop: 28 }}>Shared Services · span both practices</div>
      <div className="oc-bus" />
      <div className="acg-grid shared">
        {ACG.shared.map((s) => (
          <AcgNode key={s.id} node={{ ...s, kind: "Shared service", count: sharedCount(s) }} open={popup && popup.id === s.id}
            onClick={() => setPopup({ id: s.id, ...sharedData(s) })} />
        ))}
      </div>

      <AcgPopup data={popup} onClose={() => setPopup(null)} onJump={(office) => { setPopup(null); onJump(office); }} />
    </div>
  );
}

function OrgChart() {
  const [view, setView] = useOCState("nwdc");
  const isAcg = view === "acg";
  const cfg = OFFICES[view] || OFFICES.nwdc;
  const clock = nyDate();
  const TABS = [["nwdc", "NWDC"], ["bcdc", "BCDC"], ["acg", "ACG"]];

  return (
    <div className="lead-app orgc">
      <header className="lead-top">
        <button className="lead-back" onClick={() => window.__ocBack && window.__ocBack()} title="Back to apps"><Icon name="chevron" size={18} /></button>
        <OfficeLogos view={view} />
        <div className="lead-title">
          <h1>Org Chart</h1>
          <div className="lead-sub"><span className="lead-private-badge"><Icon name="org" size={11} /> {isAcg ? "ACG" : cfg.short}</span> {clock}</div>
        </div>
        <span style={{ flex: 1 }} />
        <div className="oc-office-toggle">
          {TABS.map(([k, lbl]) => (
            <button key={k} className={"oc-office" + (view === k ? " active" : "")} onClick={() => setView(k)}>{lbl}</button>
          ))}
        </div>
      </header>

      <div className="lead-scroll orgc-scroll">
        {isAcg ? (
          <AcgTree onJump={(office) => setView(office)} />
        ) : (
          <>
            <div className="oc-hero">
              <div className="oc-hero-text">
                <span className="eyebrow">Organization</span>
                <h2>{cfg.label}</h2>
              </div>
            </div>

            <div className="oc-tier-label">Ownership · Dr. oversight</div>
            <div className="oc-row owners">
              {cfg.owners.map((id) => <PersonChip key={id} id={id} tone="own" />)}
            </div>
            <div className="oc-stem" />

            <div className="oc-tier-label">Operations</div>
            <div className="oc-row">
              <PersonChip id={cfg.ops} label="Operations · routes & escalations" tone="ops" />
            </div>
            <div className="oc-stem" />

            <div className="oc-tier-label">Departments · source person owns intake</div>
            <div className="oc-bus" />
            <div className="oc-dept-grid">
              {cfg.departments.map((deptId) => <DeptNode key={deptId} deptId={deptId} office={view} />)}
            </div>

            {cfg.partial && (
              <div className="oc-note">Briarcliff’s local roster is still being built out — source people are set; team members fill in as we confirm them.</div>
            )}

            <div className="oc-legend">
              <span className="ocl-item"><span className="ocl-dot own" /> Ownership / Dr. oversight</span>
              <span className="ocl-item"><span className="ocl-dot ops" /> Operations</span>
              <span className="ocl-item"><span className="ocl-dot src" /> Department source person</span>
              <span className="ocl-item"><span className="ocl-dot mem" /> Team member</span>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { OrgChart });
