// CGL7 (Calls go-live #7, beyond the design's columns, built at the user's request): the cells of
// the Calls table's added columns. The design lists Transcript available (list-page.php:85); its
// call preview has Recording URL and To number, the first contact's phone (activity-preview.js:355).
import type { ReactNode } from 'react';
import { linkedSummary } from '../format';
import type { CallLinked, CallRow } from '../types';

const NONE = { total: 0, items: [] };
const muted = () => <span className="lp-muted">--</span>;

/** The recording link when it is http(s); anything else is never linked or played. */
export function recordingHref(url: string | null | undefined): string | null {
  if (!url) return null;
  try {
    const { protocol } = new URL(url);
    return protocol === 'http:' || protocol === 'https:' ? url : null;
  } catch {
    return null;
  }
}

function linkedCell<T extends { name: string }>(linked: CallLinked<T>, untitled: string) {
  const { first, more } = linkedSummary(linked);
  if (!first) return muted();
  return (
    <>
      {first.name || untitled}
      {more ? <span className="lp-muted"> +{more}</span> : null}
    </>
  );
}

/** A cell of an added column; undefined for the table's own columns (CallsListView draws them). */
export function cgl7Cell(r: CallRow, key: string): ReactNode | undefined {
  switch (key) {
    case 'dealsAssoc':
      return linkedCell(r.associations.deals, 'Untitled deal');
    case 'ticketsAssoc':
      return linkedCell(r.associations.tickets ?? NONE, 'Untitled ticket');
    case 'transcript':
      // Nothing records or transcribes calls yet (the softphone waits for Twilio).
      return 'No';
    case 'recordingUrl': {
      const href = recordingHref(r.recordingUrl);
      return href ? (
        <a className="link" href={href} target="_blank" rel="noopener noreferrer" title={href}>
          {href}
        </a>
      ) : (
        muted()
      );
    }
    case 'recording': {
      const href = recordingHref(r.recordingUrl);
      return href ? (
        <audio
          className="lp-audio"
          controls
          preload="none"
          src={href}
          aria-label={`Play the recording of ${r.title ?? 'this call'}`}
        />
      ) : (
        muted()
      );
    }
    case 'toNumber':
      return r.associations.contacts.items[0]?.phone || muted();
    default:
      return undefined;
  }
}
