// Drawer.jsx - org detail drawer
//
// Deprioritised data points are hidden from the passport per feedback
// (Andrea & Rintati). These can be inferred from the value chain, so the
// passport stays focused on what the maps actually use:
//   Global view  - hide budget, size, funding source, start year, type of
//                  financial support (financial instruments).
//   Regional view (India) - additionally hide "Regions active"; the rest of
//                  the deprioritised set is hidden too.
// `regional` is passed from app.jsx based on the active view.
function Drawer({ org, allOrgs, regional = false, onClose, onPickOrg }) {
  if (!org) return null;
  const { facets } = window.INITIATIVES_DATA;

  const typeKey = window.TYPE_KEY[org.type] || 'ngo';
  const typeShort = facets.types.short[org.type] || '';

  // Map collaborators to known orgs (fuzzy match)
  const knownLookup = new Map();
  for (const o of allOrgs) knownLookup.set(o.name.toLowerCase(), o);
  const findKnown = (name) => {
    const ln = name.toLowerCase();
    for (const [k, v] of knownLookup) {
      if (k === ln || k.includes(ln) || ln.includes(k.split('(')[0].trim())) return v;
    }
    return null;
  };

  const stop = (e) => e.stopPropagation();

  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <div className="drawer" onClick={stop}>
        <button className="drawer-close" onClick={onClose} aria-label="Close">✕</button>
        <div className="drawer-header">
          <div className="drawer-type">
            <span className={'dot dot--' + typeKey}></span>
            <span>{typeShort}</span>
            <span style={{ opacity: 0.5 }}>·</span>
            <span>{facets.types.labels[org.type] || org.type}</span>
          </div>
          <h3>{org.name}</h3>
          {/* Budget / Active since / Size removed - deprioritised data points
              (Andrea & Rintati), inferable from the value chain. */}
        </div>
        <div className="drawer-body">
          <div className="drawer-section">
            <h5>About</h5>
            <p>{org.description}</p>
          </div>

          {/* Regions active hidden in the regional (India) view - deprioritised
              there (Andrea & Rintati). Kept in the global view. */}
          {!regional && (
            <div className="drawer-section">
              <h5>Regions active</h5>
              <div className="drawer-tags">
                {org.regions.map((r) => (
                  <span key={r} className="drawer-tag region">{facets.regions.labels[r] || r}</span>
                ))}
              </div>
            </div>
          )}

          {(() => {
            // Value-chain segment tags. Global orgs carry an array in `vcRaw`;
            // India orgs store a ';'-separated string in `rawVC`. We surface the
            // raw tags (incl. "Tech provision & manufacturers", "Policymakers &
            // regulators") so the role is still visible in the passport even
            // though those no longer have dedicated columns in the table.
            const segs = (org.vcRaw && org.vcRaw.length
              ? org.vcRaw
              : (org.rawVC ? String(org.rawVC).split(/[;,]/).map(s => s.trim()) : [])
            ).filter(v => v && !v.startsWith('N/A'));
            if (segs.length === 0) return null;
            return (
              <div className="drawer-section">
                <h5>Energy ecosystem segments</h5>
                <div className="drawer-tags">
                  {segs.map((v) => (
                    <span key={v} className="drawer-tag">{v}</span>
                  ))}
                </div>
              </div>
            );
          })()}

          <div className="drawer-section">
            <h5>Barriers addressed</h5>
            <div className="drawer-tags">
              {org.barriers.map((b) => (
                <span key={b} className="drawer-tag barrier">{b}</span>
              ))}
            </div>
          </div>

          {org.collaborators.length > 0 && (
            <div className="drawer-section">
              <h5>Publicly works with</h5>
              <div className="collab-list">
                {org.collaborators.map((c, i) => {
                  const known = findKnown(c);
                  return (
                    <div
                      key={i}
                      className={'collab-item ' + (known ? 'is-known' : 'is-external')}
                      onClick={() => known && onPickOrg(known)}
                      style={{ cursor: known ? 'pointer' : 'default' }}
                    >
                      {c}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {org.source && (
            <div className="drawer-section">
              <h5>Source</h5>
              <a href={org.source} target="_blank" rel="noopener">{org.source}</a>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
window.Drawer = Drawer;
