// Project Workspace shell — header, section nav, and route to a section body.

const PW_SECTIONS = [
  { key: 'overview',    label: 'Overview',    icon: 'compass' },
  { key: 'plan',        label: 'Plan',        icon: 'stages' },
  { key: 'features',    label: 'Features',    icon: 'features' },
  { key: 'research',    label: 'Research',    icon: 'flask' },
  { key: 'design',      label: 'Design',      icon: 'palette' },
  { key: 'development', label: 'Development', icon: 'terminal' },
  { key: 'commercial',  label: 'Commercial',  icon: 'wallet' },
  { key: 'documents',   label: 'Documents',   icon: 'files' },
];

function ProjectWorkspace({ projectId, section = 'overview', subId = null, sub2 = null, data }) {
  const pdata = window.MYGENI_PROJECT_DATA[projectId];
  if (!pdata) {
    return (
      <main className="main">
        <Card>
          <EmptyState
            illustration={<NoResultsIllus size={140} />}
            title={`We don't have a full workspace built for that project yet`}
            body="The My Geni project has the deepest sample content — open it to explore."
            action={<button className="btn btn-primary btn-sm" onClick={() => location.hash = '#/projects/p-mh-portal/overview'}>Open My Geni</button>}
          />
        </Card>
      </main>
    );
  }
  const client = data.clients[pdata.client];
  const contract = pdata.contract ? data.contracts.find(c => c.id === pdata.contract) : null;
  const stage = pdata.stages.find(s => s.n === pdata.currentStage);

  // Attention-focused counters only. Decorative "how many exist" counts are
  // omitted — the sidebar rule (badges = attention) applies to the section
  // nav too. Show a count only when there's something that needs the user.
  const projectContractsInProject = data.contracts.filter(c => c.project === pdata.id);
  const expiringContracts = projectContractsInProject.filter(c => c.reminder === 'expiring').length;
  const blockedFeatures   = pdata.features.filter(f => f.blocked).length;
  const cnts = {
    features: blockedFeatures > 0 ? blockedFeatures : null,
    commercial: expiringContracts > 0 ? expiringContracts : null,
    plan: null, research: null, design: null, development: null, documents: null,
  };
  const cntTones = {
    features: 'red', commercial: 'yellow',
  };

  return (
    <div data-screen-label={`PW ${pdata.name}`}>
      {/* Sticky project chrome */}
      <div className="pw-chrome">
        <ProjectBreadcrumb pdata={pdata} data={data} />
        <ProjectHeader pdata={pdata} client={client} contract={contract} stage={stage} />
        <div className="pw-nav">
          {PW_SECTIONS.map((s) => (
            <a
              key={s.key}
              className={`pw-nav-item${section === s.key ? ' active' : ''}`}
              href={`#/projects/${projectId}/${s.key}`}
            >
              <Icon name={s.icon} size={16} strokeWidth={1.75} />
              <span>{s.label}</span>
              {cnts[s.key] != null && (
                <span className={`n-count${cntTones[s.key] ? ' n-tone-' + cntTones[s.key] : ''}`}>
                  {cnts[s.key]}
                </span>
              )}
            </a>
          ))}
        </div>
      </div>

      {/* Section body */}
      <div className="pw-body">
        {section === 'overview'    && <OverviewSection      pdata={pdata} client={client} contract={contract} stage={stage} />}
        {section === 'plan'        && <StagesSection        pdata={pdata} />}
        {section === 'features'    && <FeaturesSection      pdata={pdata} featureId={subId} />}
        {section === 'research'    && <ResearchWorkspaceV2  pdata={pdata} subId={subId} sub2={sub2} />}
        {section === 'design'      && <DesignWorkspaceV2    pdata={pdata} subId={subId} sub2={sub2} />}
        {section === 'development' && <DevelopmentWorkspaceV2 pdata={pdata} subId={subId} sub2={sub2} />}
        {section === 'commercial'  && <CommercialWorkspaceV2 pdata={pdata} data={data} subId={subId} sub2={sub2} />}
        {section === 'documents'   && <DocumentsWorkspaceV2 pdata={pdata} subId={subId} sub2={sub2} />}
      </div>
    </div>
  );
}

// ---------- BREADCRUMB BAR ----------
// This bar answers "where am I?" and "how do I go back?" without extra chrome.
function ProjectBreadcrumb({ pdata, data }) {
  const [switcherOpen, setSwitcherOpen] = React.useState(false);
  const statusToneMap = {
    'On track':  'green', 'At risk': 'red', 'Blocked': 'red',
    'In review': 'blue',  'Design':  'purple', 'Kickoff': 'purple',
    'Building':  'yellow',
  };
  const others = (data.projects || []).filter(p => p.id !== pdata.id).slice(0, 6);

  return (
    <div className="pw-crumb">
      <a className="pw-crumb-back" href="#/projects" aria-label="Back to Projects">
        <Icon name="chevronL" size={14} strokeWidth={2} />
        <Icon name="projects" size={14} strokeWidth={1.75} />
        <span>Projects</span>
      </a>
      <span className="pw-crumb-sep">/</span>
      <div className="pw-crumb-project">
        <span className="pw-crumb-name">{pdata.name}</span>
        <Label tone={statusToneMap[pdata.status] || 'gray'} dot size="sm">{pdata.status}</Label>
      </div>
      <div className="pw-crumb-spacer" />
      <button
        className="pw-crumb-switch"
        onClick={() => setSwitcherOpen(v => !v)}
        aria-expanded={switcherOpen}
        aria-label="Switch project"
      >
        <Icon name="layers2" size={14} strokeWidth={1.75} />
        <span>Switch project</span>
        <Icon name="caretDown" size={12} strokeWidth={1.75} />
      </button>

      {switcherOpen && (
        <div className="pw-switcher" role="menu">
          <div className="pw-switcher-head">
            <span>Switch to</span>
            <a href="#/projects" className="pw-switcher-all">See all projects →</a>
          </div>
          <div className="pw-switcher-list">
            {others.map((p) => (
              <a href={`#/projects/${p.id}/overview`} className="pw-switcher-item" key={p.id} onClick={() => setSwitcherOpen(false)}>
                <div className="kind-square kind-sky" style={{ width: 26, height: 26, borderRadius: 8 }}>
                  <Icon name="projects" size={13} strokeWidth={1.75} />
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div className="pw-switcher-name truncate">{p.name}</div>
                  <div className="pw-switcher-meta">{data.clients[p.client]?.name || 'Internal'} · Stage {p.stageN || '—'}</div>
                </div>
                <Label tone={statusToneMap[p.status] || 'gray'} dot size="sm">{p.status}</Label>
              </a>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- HEADER ----------
function ProjectHeader({ pdata, client, contract, stage }) {
  const statusToneMap = {
    'On track':  'green',
    'At risk':   'red',
    'Blocked':   'red',
    'In review': 'blue',
    'Design':    'purple',
    'Kickoff':   'purple',
    'Building':  'yellow',
  };

  return (
    <div className="pw-header">
      <div className="pw-title-block">
        <div className="pw-title-row">
          <h1 className="pw-title">{pdata.name}</h1>
          <span className="pw-code">{pdata.code}</span>
          <Label tone={statusToneMap[pdata.status] || 'gray'} dot size="sm">{pdata.status}</Label>
        </div>
        <p className="pw-tagline">{pdata.tagline}</p>
        <div className="pw-meta">
          <div className="pw-meta-item">
            <Icon name="person" size={14} strokeWidth={1.75} />
            <span>Owner <b>{pdata.owner}</b></span>
          </div>
          <div className="pw-meta-item">
            <AvatarStack names={pdata.team.map(t => t.name)} max={4} size="xs" />
            <span>{pdata.team.length} people</span>
          </div>
          {client && client.short !== '·' && (
            <>
              <div className="pw-meta-item"><span className="divider" /></div>
              <div className="pw-meta-item">
                <ClientChip client={client} />
              </div>
            </>
          )}
          {contract && (
            <div className="pw-meta-item">
              <ContractChip id={contract.id} tone={contract.reminder === 'expiring' ? 'warn' : ''} />
            </div>
          )}
          {pdata.risk && (
            <div className="pw-meta-item">
              <Label tone="red" dot size="sm">{pdata.risk === 'blocked' ? 'Blocked' : 'At risk'}</Label>
            </div>
          )}
        </div>
      </div>

      <div className="pw-stats">
        <div className="pw-stat ring-stat">
          <Ring percent={pdata.progress} color="var(--primary-01)" size={44} />
          <div>
            <div className="lbl">Progress</div>
            <div className="val tabular">{pdata.progress}%</div>
          </div>
        </div>
        <div className="pw-stat">
          <div className="lbl">Current stage</div>
          <div className="val">{String(pdata.currentStage).padStart(2, '0')} · {stage?.name}</div>
          <div className="sub">Stage {pdata.currentStage} of {pdata.stages.length}</div>
        </div>
        <div className="pw-stat">
          <div className="lbl">Next milestone</div>
          <div className="val">{pdata.targetMilestone.name}</div>
          <div className="sub">{pdata.targetMilestone.date} · in {pdata.targetMilestone.when} days</div>
        </div>
        <div className="pw-actions">
          <button className="icon-btn" title="Share" aria-label="Share">
            <Icon name="share" size={16} strokeWidth={1.75} />
          </button>
          <button className="btn btn-primary btn-sm">
            <Icon name="edit" size={14} strokeWidth={1.75} />
            <span>Update</span>
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProjectWorkspace, PW_SECTIONS });
