/* ============================================================
   Pipeline list view — sortable table of assessed sites
   ============================================================ */

const PC_COLS = [
  { key: 'name',          label: 'Site',          num: false },
  { key: 'region',        label: 'Region',        num: false },
  { key: 'area_ha',       label: 'Area (ha)',     num: true },
  { key: 'overall_score', label: 'Score',         num: true },
  { key: 'overall_status',label: 'Status',        num: false },
  { key: 'assessed_at',   label: 'Assessed',      num: false },
];

const STATUS_RANK = { green: 4, amber: 3, red: 2, unknown: 1 };

function scoreColor(status) {
  return { green: 'var(--st-green)', amber: 'var(--st-amber)', red: 'var(--st-red)', unknown: 'var(--st-unknown)' }[status] || 'var(--st-unknown)';
}

const Pipeline = ({ sites, onOpen }) => {
  const [sort, setSort] = React.useState({ key: 'overall_score', dir: 'desc' });

  const sorted = React.useMemo(() => {
    const arr = [...sites];
    const { key, dir } = sort;
    arr.sort((a, b) => {
      let av, bv;
      if (key === 'overall_status') { av = STATUS_RANK[a.overall_status]; bv = STATUS_RANK[b.overall_status]; }
      else if (key === 'overall_score') { av = a.overall_score == null ? -1 : a.overall_score; bv = b.overall_score == null ? -1 : b.overall_score; }
      else { av = a[key]; bv = b[key]; }
      if (typeof av === 'string') { av = av.toLowerCase(); bv = bv.toLowerCase(); }
      if (av < bv) return dir === 'asc' ? -1 : 1;
      if (av > bv) return dir === 'asc' ? 1 : -1;
      return 0;
    });
    return arr;
  }, [sites, sort]);

  const toggle = key => setSort(s => s.key === key ? { key, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: key === 'name' || key === 'region' ? 'asc' : 'desc' });

  const stats = React.useMemo(() => {
    const c = { green: 0, amber: 0, red: 0, unknown: 0 };
    sites.forEach(s => c[s.overall_status]++);
    return c;
  }, [sites]);

  return (
    <div className="pc-pipeline">
      <div className="pc-pipe-inner">
        <div className="pc-pipe-head">
          <div>
            <div className="eyebrow">Prospecting pipeline</div>
            <h1>Every site we’ve <span className="accent">screened</span></h1>
          </div>
          <button className="pc-btn pc-btn-outline" onClick={() => onOpen(null)}>{PCI.plus}New assessment</button>
        </div>
        <p className="pc-pipe-sub">Ranked fast-screen results across Hawke’s Bay, Northland and the Bay of Plenty. Open any site to view it on the map and read the full report.</p>

        <div className="pc-pipe-stats">
          <div className="pc-pipe-stat"><div className="num">{sites.length}</div><div className="lbl">Sites assessed</div></div>
          <div className="pc-pipe-stat"><div className="num">{stats.green}</div><div className="lbl"><span className="sw" style={{ background: 'var(--st-green)' }} />Strong prospects</div></div>
          <div className="pc-pipe-stat"><div className="num">{stats.amber}</div><div className="lbl"><span className="sw" style={{ background: 'var(--st-amber)' }} />Needs a closer look</div></div>
          <div className="pc-pipe-stat"><div className="num">{stats.red + stats.unknown}</div><div className="lbl"><span className="sw" style={{ background: 'var(--st-red)' }} />Flagged or pending</div></div>
        </div>

        <div className="pc-table-wrap">
          <table className="pc-table">
            <thead>
              <tr>
                {PC_COLS.map(col => (
                  <th key={col.key} className={`${col.num ? 'num' : ''} ${sort.key === col.key ? 'sorted' : ''}`} onClick={() => toggle(col.key)}>
                    {col.label}<span className="arrow">{sort.key === col.key ? (sort.dir === 'asc' ? '▲' : '▼') : '▾'}</span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {sorted.map(s => (
                <tr key={s.id} onClick={() => onOpen(s.id)}>
                  <td>
                    <div className="site-name">{s.name}</div>
                    <div className="site-addr">{s.address}</div>
                  </td>
                  <td>{s.region}</td>
                  <td className="num">{s.area_ha.toFixed(1)}</td>
                  <td className="num">
                    <span className="score-cell" style={{ color: scoreColor(s.overall_status) }}>{s.overall_score == null ? '–' : s.overall_score}</span>
                    <span className="pc-scorebar"><i style={{ width: `${s.overall_score || 0}%`, background: scoreColor(s.overall_status) }} /></span>
                  </td>
                  <td><StatusPill status={s.overall_status} /></td>
                  <td>{s.assessed_at}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

window.Pipeline = Pipeline;
