/* Organisation chart — company hierarchy with filled roles (+ assigned
   responsibilities), planned open positions, and actively-hiring positions
   that link straight to their job detail. Staff use obvious placeholder names;
   the "hiring" nodes are injected live from the jobs prop (status === 'open'). */
const OG = window.GreydigiComponents;
const { Avatar: OAvatar } = OG;

const ORG_CEO = {
  name: 'Jordan Doe', initials: 'JD', title: 'Founder & CEO',
  responsibilities: ['Company vision & strategy', 'Fundraising & key client accounts', 'Hiring bar & culture'],
};

const ORG_DEPTS = [
  {
    key: 'Engineering',
    lead: {
      name: 'Taylor Doe', initials: 'TD', title: 'Head of Engineering',
      responsibilities: ['Agent platform architecture', 'Engineering standards & reviews', 'Technical hiring'],
    },
    reports: [
      {
        type: 'filled', name: 'Jamie Doe', initials: 'JA', title: 'Senior Forward Deployed Engineer',
        responsibilities: ['Client-side agent deployments', 'Production reliability & on-call'],
      },
      {
        type: 'open', title: 'ML Engineer', note: 'Planned — Q3 headcount',
        responsibilities: ['Model evaluation & fine-tuning', 'Retrieval quality'],
      },
    ],
  },
  {
    key: 'Delivery',
    lead: {
      name: 'Riley Doe', initials: 'RL', title: 'Head of Delivery',
      responsibilities: ['End-to-end delivery governance', 'Client success & outcomes', 'Delivery playbooks'],
    },
    reports: [
      {
        type: 'filled', name: 'Avery Doe', initials: 'AV', title: 'Delivery Lead',
        responsibilities: ['Scoping & handover', 'Stakeholder management'],
      },
      {
        type: 'open', title: 'Solutions Consultant', note: 'Planned — Q4 headcount',
        responsibilities: ['Pre-sales solutioning', 'Workflow design'],
      },
    ],
  },
  {
    key: 'Operations',
    lead: {
      name: 'Skyler Doe', initials: 'SK', title: 'Head of Operations',
      responsibilities: ['Internal process ownership', 'Finance & HR coordination', 'Vendor management'],
    },
    reports: [
      {
        type: 'open', title: 'Finance & People Coordinator', note: 'Planned — H2 headcount',
        responsibilities: ['Payroll & HR administration', 'Bookkeeping & compliance support'],
      },
    ],
  },
];

/* ---------- single node ---------- */
function OrgNode({ node, onOpenJob }) {
  const hiring = node.type === 'hiring';
  const open = node.type === 'open';
  const cls =
    'org-card' +
    (node.type === 'ceo' ? ' is-ceo' : '') +
    (node.type === 'lead' ? ' is-lead' : '') +
    (open ? ' is-open' : '') +
    (hiring ? ' is-hiring' : '');
  const clickable = hiring && node.jobId;
  const Tag = clickable ? 'button' : 'div';
  const props = clickable ? { type: 'button', onClick: () => onOpenJob(node.jobId) } : {};

  return (
    <Tag className={cls} {...props}>
      <div className="org-card-top">
        {open ? (
          <span className="org-ghost"><Icon name="userPlus" size={18} /></span>
        ) : hiring ? (
          <span className="org-jobico"><Icon name="briefcase" size={16} /></span>
        ) : (
          <OAvatar initials={node.initials} size={node.type === 'ceo' ? 'md' : 'sm'} color="charcoal" />
        )}
        <div className="org-card-id">
          <div className="org-card-name">{open || hiring ? node.title : node.name}</div>
          <div className="org-card-role">
            {node.type === 'ceo' || node.type === 'lead' || node.type === 'filled'
              ? node.title
              : open ? 'Open position' : 'Actively hiring'}
          </div>
        </div>
        {node.type === 'ceo' && <span className="org-tag ceo"><Icon name="crown" size={11} /> CEO</span>}
        {node.type === 'lead' && <span className="org-tag lead">Lead</span>}
        {open && <span className="org-tag open">Open</span>}
        {hiring && <span className="org-tag hiring"><Icon name="sparkles" size={10} /> Hiring</span>}
      </div>

      {node.responsibilities && (
        <ul className="org-resp">
          {node.responsibilities.map((r, i) => (
            <li key={i}><Icon name="check" size={11} /> {r}</li>
          ))}
        </ul>
      )}

      {open && node.note && <div className="org-note">{node.note}</div>}

      {hiring && (
        <div className="org-hiring-foot">
          <span className="org-applicants">{node.applicants} applicant{node.applicants !== 1 ? 's' : ''} · {node.stage}</span>
          <span className="org-open-link">View job <Icon name="chevronRight" size={13} /></span>
        </div>
      )}
    </Tag>
  );
}

/* ---------- org chart view ---------- */
function OrgChartView({ jobs, candidates, onOpenJob }) {
  const openJobs = jobs.filter((j) => j.status === 'open');
  const applicantsOf = (id) => candidates.filter((c) => c.jobId === id).length;

  const hiringByDept = {};
  openJobs.forEach((j) => {
    (hiringByDept[j.dept] = hiringByDept[j.dept] || []).push({
      type: 'hiring', title: j.title, jobId: j.id, applicants: applicantsOf(j.id), stage: j.stage,
    });
  });

  const filledCount =
    1 + ORG_DEPTS.length +
    ORG_DEPTS.reduce((n, d) => n + d.reports.filter((r) => r.type === 'filled').length, 0);
  const openCount = ORG_DEPTS.reduce((n, d) => n + d.reports.filter((r) => r.type === 'open').length, 0);

  return (
    <div className="view-scroll">
      <div className="view-inner view-wide">
        <PageHead title="Organisation Chart" subtitle="Greydigi · team, responsibilities & open roles" />

        <div className="org-summary">
          <div className="org-stat"><span className="org-stat-n">{filledCount}</span><span className="org-stat-l">People</span></div>
          <div className="org-stat"><span className="org-stat-n org-stat-coral">{openJobs.length}</span><span className="org-stat-l">Actively hiring</span></div>
          <div className="org-stat"><span className="org-stat-n">{openCount}</span><span className="org-stat-l">Open positions</span></div>
          <div className="org-legend">
            <span className="org-leg"><span className="org-leg-dot filled" /> Filled</span>
            <span className="org-leg"><span className="org-leg-dot open" /> Open position</span>
            <span className="org-leg"><span className="org-leg-dot hiring" /> Actively hiring</span>
          </div>
        </div>

        <div className="org-tree">
          <div className="org-ceo-row">
            <OrgNode node={{ ...ORG_CEO, type: 'ceo' }} />
          </div>
          <div className="org-trunk" />
          <div className="org-depts">
            {ORG_DEPTS.map((d) => {
              const reports = [
                ...d.reports.filter((r) => r.type === 'filled'),
                ...(hiringByDept[d.key] || []),
                ...d.reports.filter((r) => r.type === 'open'),
              ];
              return (
                <div key={d.key} className="org-dept">
                  <div className="org-dept-label">{d.key}</div>
                  <OrgNode node={{ ...d.lead, type: 'lead' }} />
                  <div className="org-reports">
                    {reports.map((r, i) => <OrgNode key={i} node={r} onOpenJob={onOpenJob} />)}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OrgChartView });
