/* MY GENI — Phase 22 · Clients Workspace v2
 *
 * Three peer views (Overview / Directory / Client Detail).
 * Depth cap: 1 (clients → client detail).
 * Intentionally NOT a CRM. No pipeline, no forecasting, no MRR.
 * Everything demo remains clearly illustrative.
 *
 * Routes: #/clients, #/clients/directory, #/clients/:id
 */

function ClientsWorkspaceV2({ data, subId, sub2 }) {
  // subId is the second route part after "clients". For #/clients → subId=null.
  // For #/clients/directory → subId="directory". For #/clients/<id> → subId=<id>.
  const clients = data.clients || {};
  const clientList = Object.keys(clients).map(k => ({ id: k, ...clients[k] }));

  // If subId is a known non-view keyword ("directory"), show the directory.
  // Otherwise if subId matches a client key, show detail. Otherwise Overview.
  let mode = 'overview';
  let openClient = null;
  if (subId === 'directory') mode = 'directory';
  else if (subId && clients[subId]) { mode = 'detail'; openClient = { id: subId, ...clients[subId] }; }

  const contracts = (data.contracts || []).filter(c => !!c.client);

  return (
    <main className="main cw2-main" data-screen-label={
      mode === 'detail' ? '14 Clients · Detail' :
      mode === 'directory' ? '14 Clients · Directory' :
      '14 Clients'
    }>
      <div className="cw2-header">
        <div>
          <h1 className="greeting">Clients</h1>
          <div className="date-line">
            {clientList.length === 0 ? 'No relationships yet' :
              <>{clientList.length} relationship{clientList.length === 1 ? '' : 's'} · all illustrative · MY GENI is currently internal</>}
          </div>
        </div>
        <div className="cw2-tabs">
          <a href="#/clients"           className={`cw2-tab ${mode === 'overview'  ? 'active' : ''}`}>Overview</a>
          <a href="#/clients/directory" className={`cw2-tab ${mode === 'directory' ? 'active' : ''}`}>Directory</a>
        </div>
      </div>

      {mode === 'overview'  && <CW2Overview  data={data} clients={clientList} contracts={contracts} />}
      {mode === 'directory' && <CW2Directory data={data} clients={clientList} contracts={contracts} />}
      {mode === 'detail'    && <CW2Detail    data={data} client={openClient} contracts={contracts} />}
    </main>
  );
}

// ---- Overview ----------------------------------------------------
function CW2Overview({ data, clients, contracts }) {
  // Active relationship = the one currently attached to the flagship project via a Template contract.
  const active = clients.find(c => c.id === 'portside') || clients[0];
  const activeContract = contracts.find(c => c.client === active?.id);
  const projects = (data.projects || []).filter(p => p.client === active?.id);
  const owner = activeContract?.owner || 'Alireza Izadi';

  return (
    <div className="cw2-body">
      {/* Illustrative relationship summary + active partner card */}
      <div className="cw2-active-card">
        <div className="cw2-active-left">
          <div className="cw2-eyebrow"><span className="cw2-dot" /> <span>Active engagement</span></div>
          <h2 className="cw2-active-title">{active?.name || 'Founding Design Partner'}</h2>
          <p className="cw2-active-sub">
            {active?.industry || 'Illustrative partner · template'} — this is the illustrative engagement that MY GENI uses to demonstrate how partner relationships flow through the product. No real signed contract.
          </p>
          <div className="cw2-active-meta">
            <div className="cw2-meta-row">
              <span className="cw2-meta-k">Relationship owner</span>
              <span className="cw2-meta-v"><Avatar name={owner} size="xs" /> {owner}</span>
            </div>
            <div className="cw2-meta-row">
              <span className="cw2-meta-k">Status</span>
              <Label tone="blue" dot>Template</Label>
            </div>
            <div className="cw2-meta-row">
              <span className="cw2-meta-k">Contact</span>
              <span className="cw2-meta-v">{activeContract?.clientContact || 'Founding partner'} · To be assigned</span>
            </div>
          </div>
        </div>
        <div className="cw2-active-right">
          <div className="cw2-projects-lbl">Linked projects</div>
          {projects.length === 0 && <div className="cw2-empty-inline">No projects linked yet.</div>}
          {projects.map(p => (
            <a key={p.id} className="cw2-project-row" href={`#/projects/${p.id}/overview`}>
              <span className="cw2-project-glyph">{p.code?.slice(0, 3) || 'MYG'}</span>
              <div className="cw2-project-meta">
                <div className="cw2-project-name">{p.name}</div>
                <div className="cw2-project-code mono">{p.code}</div>
              </div>
              <Label tone={p.statusTone || 'blue'} dot>{p.status}</Label>
            </a>
          ))}
          <a className="cw2-cta" href={`#/clients/${active?.id || 'portside'}`}>
            Open relationship
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 5l7 7-7 7" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </a>
        </div>
      </div>

      {/* Recent activity — illustrative rows */}
      <div className="cw2-section">
        <div className="cw2-section-head">
          <h3 className="cw2-section-title">Recent activity</h3>
          <span className="cw2-section-hint">Illustrative — this is what a live relationship stream would show</span>
        </div>
        <div className="cw2-activity">
          <CW2ActivityRow icon="signed"  when="Feb 04" who="Founding partner" what={<>Signed the <b>Discovery scope acceptance memo</b>.</>} />
          <CW2ActivityRow icon="waiting" when="Sep 22" who="Alireza Izadi"   what={<>Sent <b>v2 scope PDF</b> for founding-partner countersignature.</>} />
          <CW2ActivityRow icon="milestone" when="Sep 26" who="System"        what={<>Milestone <b>Design partner sign-off on v2 scope</b> is due.</>} />
          <CW2ActivityRow icon="upcoming" when="Oct 02" who="System"         what={<>Milestone <b>Wave 2 Beta milestone</b> upcoming — illustrative $54K.</>} />
        </div>
      </div>

      {/* Capacity state */}
      <div className="cw2-empty-block">
        <div className="cw2-empty-title">Room for more relationships</div>
        <div className="cw2-empty-sub">MY GENI is currently internal. New engagements will appear here.</div>
      </div>
    </div>
  );
}

function CW2ActivityRow({ icon, when, who, what }) {
  const glyph = {
    signed:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12l4 4L19 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>,
    waiting:   <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.6"/><path d="M12 7v5l3 2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>,
    milestone: <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" fill="currentColor" /></svg>,
    upcoming:  <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="8" stroke="currentColor" strokeWidth="1.6" strokeDasharray="2 3"/></svg>,
  }[icon] || null;
  return (
    <div className="cw2-activity-row">
      <div className="cw2-activity-icon">{glyph}</div>
      <div className="cw2-activity-when">{when}</div>
      <div className="cw2-activity-who"><Avatar name={who} size="xs" /> {who}</div>
      <div className="cw2-activity-what">{what}</div>
    </div>
  );
}

// ---- Directory ---------------------------------------------------
function CW2Directory({ data, clients, contracts }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');

  const filtered = clients.filter(c => {
    if (filter === 'illustrative' && !/[Ii]llustrative/.test(c.industry || '')) return false;
    if (filter === 'internal'     && c.id !== 'internal')                       return false;
    if (q.trim()) {
      const h = [c.name, c.industry, c.id].join(' ').toLowerCase();
      if (!h.includes(q.trim().toLowerCase())) return false;
    }
    return true;
  });

  return (
    <div className="cw2-body">
      <div className="cw2-directory-controls">
        <div className="cw2-search">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
            <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.7"/>
            <path d="M20 20l-3.5-3.5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/>
          </svg>
          <input
            type="text"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search relationships…"
          />
        </div>
        <div className="cw2-filters">
          {[
            ['all',          'All',          clients.length],
            ['illustrative', 'Illustrative', clients.filter(c => /[Ii]llustrative/.test(c.industry || '')).length],
            ['internal',     'Internal',     clients.filter(c => c.id === 'internal').length],
          ].map(([k, label, count]) => (
            <button key={k}
                    className={`cw2-chip ${filter === k ? 'active' : ''}`}
                    onClick={() => setFilter(k)}>
              {label} <span className="cw2-chip-count">{count}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="cw2-rows">
        {filtered.length === 0 && <div className="cw2-empty-inline">No relationships match those filters.</div>}
        {filtered.map(c => {
          const cContracts = contracts.filter(ct => ct.client === c.id);
          const projects   = (data.projects || []).filter(p => p.client === c.id);
          const owner      = cContracts[0]?.owner || 'Alireza Izadi';
          return (
            <a key={c.id} className="cw2-row" href={`#/clients/${c.id}`}>
              <div className="cw2-row-glyph" style={{ background: c.color || '#E2E2E2' }}>{c.short || c.name.slice(0, 2)}</div>
              <div className="cw2-row-main">
                <div className="cw2-row-name">{c.name}</div>
                <div className="cw2-row-industry">{c.industry}</div>
              </div>
              <div className="cw2-row-col">
                <span className="cw2-row-k">Projects</span>
                <span className="cw2-row-v">{projects.length}</span>
              </div>
              <div className="cw2-row-col">
                <span className="cw2-row-k">Contracts</span>
                <span className="cw2-row-v">{cContracts.length}</span>
              </div>
              <div className="cw2-row-col">
                <span className="cw2-row-k">Owner</span>
                <span className="cw2-row-v"><Avatar name={owner} size="xs" /> <span>{owner.split(' ')[0]}</span></span>
              </div>
              <div className="cw2-row-status">
                {c.id === 'internal'
                  ? <Label tone="gray" dot>Internal</Label>
                  : <Label tone="blue" dot>Illustrative</Label>}
              </div>
            </a>
          );
        })}
      </div>
    </div>
  );
}

// ---- Client Detail -----------------------------------------------
function CW2Detail({ data, client, contracts }) {
  const projects = (data.projects || []).filter(p => p.client === client.id);
  const clientContracts = contracts.filter(c => c.client === client.id);
  const owner = clientContracts[0]?.owner || 'Alireza Izadi';
  const contact = clientContracts[0]?.clientContact || 'To be assigned';

  // Linked documents — pull from the project's canonical documents that reference these contracts
  const linkedDocs = [];
  (data.projects || []).forEach(p => {
    if (p.client !== client.id) return;
    const pd = window.MYGENI_PROJECT_DATA?.[p.id];
    if (!pd) return;
    (pd.documents || []).forEach(d => {
      if (d.contract && clientContracts.some(c => c.id === d.contract)) linkedDocs.push({ ...d, projectId: p.id });
    });
  });

  return (
    <div className="cw2-body">
      <a className="cw2-back" href="#/clients/directory">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M15 6l-6 6 6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
        <span>Back to Directory</span>
      </a>

      <div className="cw2-detail-head">
        <div className="cw2-detail-mark" style={{ background: client.color || '#E2E2E2' }}>{client.short || client.name.slice(0, 2)}</div>
        <div className="cw2-detail-id">
          <div className="cw2-eyebrow"><span>CLIENT · {client.id.toUpperCase()}</span></div>
          <h2 className="cw2-detail-name">{client.name}</h2>
          <div className="cw2-detail-sub">{client.industry}</div>
        </div>
        <div className="cw2-detail-rail">
          {client.id === 'internal'
            ? <Label tone="gray" dot>Internal · founding team</Label>
            : <Label tone="blue" dot>Illustrative · template</Label>}
        </div>
      </div>

      <div className="cw2-detail-grid">
        <div className="cw2-detail-main">
          {/* Relationship summary */}
          <div className="cw2-panel">
            <div className="cw2-panel-h">Relationship summary</div>
            <p className="cw2-panel-p">
              {client.id === 'portside'
                ? <>An illustrative engagement template — MY GENI uses this to demonstrate how a founding-partner relationship would flow through Stages 01 → 07. When a real founding partner is signed, this record becomes the canonical relationship without any component changes.</>
                : <>{client.name} is the internal owning entity for MY GENI itself.</>}
            </p>
          </div>

          {/* Activity timeline */}
          <div className="cw2-panel">
            <div className="cw2-panel-h">Activity timeline</div>
            <div className="cw2-activity">
              <CW2ActivityRow icon="signed"    when="Feb 04" who="Founding partner" what={<>Signed the <b>Discovery scope acceptance memo</b>.</>} />
              <CW2ActivityRow icon="milestone" when="Sep 12" who="Alireza Izadi"   what={<>Countersigned <b>the illustrative Founding Design Partner engagement template</b>.</>} />
              <CW2ActivityRow icon="waiting"   when="Sep 22" who="Alireza Izadi"   what={<>Sent <b>v2 scope PDF</b> for founding-partner countersignature.</>} />
              <CW2ActivityRow icon="upcoming"  when="Oct 02" who="System"          what={<>Wave 2 Beta milestone upcoming — illustrative $54K.</>} />
            </div>
          </div>

          {/* Linked projects */}
          <div className="cw2-panel">
            <div className="cw2-panel-h">Linked projects <span className="cw2-panel-hint">{projects.length}</span></div>
            {projects.length === 0
              ? <div className="cw2-empty-inline">No projects yet.</div>
              : projects.map(p => (
                  <a key={p.id} className="cw2-project-row cw2-project-row-wide" href={`#/projects/${p.id}/overview`}>
                    <span className="cw2-project-glyph">{p.code?.slice(0, 3) || 'MYG'}</span>
                    <div className="cw2-project-meta">
                      <div className="cw2-project-name">{p.name}</div>
                      <div className="cw2-project-code mono">{p.code}</div>
                    </div>
                    <span className="cw2-project-owner"><Avatar name={p.owner} size="xs" /> {p.owner.split(' ')[0]}</span>
                    <Label tone={p.statusTone || 'blue'} dot>{p.status}</Label>
                  </a>
                ))}
          </div>

          {/* Linked documents */}
          {linkedDocs.length > 0 && (
            <div className="cw2-panel">
              <div className="cw2-panel-h">Linked documents <span className="cw2-panel-hint">{linkedDocs.length}</span></div>
              {linkedDocs.slice(0, 4).map(d => (
                <a key={d.id} className="cw2-doc-row" href={`#/projects/${d.projectId}/documents/doc/${d.id}`}>
                  <span className="cw2-doc-kind mono">{(d.kindKey || 'DOC').toUpperCase().slice(0, 4)}</span>
                  <div className="cw2-doc-title">{d.title}</div>
                  <div className="cw2-doc-meta">{d.state || 'draft'} · {d.owner || '—'}</div>
                </a>
              ))}
            </div>
          )}
        </div>

        {/* Right rail */}
        <div className="cw2-detail-rail-col">
          <div className="cw2-rail-panel">
            <div className="cw2-rail-h">Primary contact</div>
            <div className="cw2-rail-contact">
              <Avatar name={contact} size="lg" />
              <div>
                <div className="cw2-rail-contact-name">{contact}</div>
                <div className="cw2-rail-contact-role">{client.name}</div>
              </div>
            </div>
          </div>

          <div className="cw2-rail-panel">
            <div className="cw2-rail-h">Relationship owner</div>
            <a className="cw2-rail-owner" href="#/">
              <Avatar name={owner} size="sm" />
              <div>
                <div className="cw2-rail-owner-name">{owner}</div>
                <div className="cw2-rail-owner-role">Product Operations</div>
              </div>
            </a>
          </div>

          <div className="cw2-rail-panel">
            <div className="cw2-rail-h">At a glance</div>
            <div className="cw2-rail-facts">
              <div><span className="cw2-rail-k">Projects</span><span className="cw2-rail-v">{projects.length}</span></div>
              <div><span className="cw2-rail-k">Contracts</span><span className="cw2-rail-v">{clientContracts.length}</span></div>
              <div><span className="cw2-rail-k">Documents</span><span className="cw2-rail-v">{linkedDocs.length}</span></div>
              <div><span className="cw2-rail-k">Status</span><span className="cw2-rail-v">{client.id === 'internal' ? 'Internal' : 'Illustrative'}</span></div>
            </div>
          </div>

          {clientContracts.length > 0 && (
            <div className="cw2-rail-panel">
              <div className="cw2-rail-h">Commercial context</div>
              {clientContracts.map(c => (
                <a key={c.id} className="cw2-rail-contract" href={`#/projects/${c.project}/commercial/contract/${c.id}`}>
                  <div className="cw2-rail-contract-code mono">{c.id}</div>
                  <div className="cw2-rail-contract-title">{c.title}</div>
                  <div className="cw2-rail-contract-meta">{c.status} · {c.value}</div>
                </a>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClientsWorkspaceV2 });
