window.SelectionBar = function SelectionBar({
  count, total, ctaLabel, onCTA, onClear, onSelectAll, icon,
  secondaryLabel, onSecondary, secondaryIcon,
  // Optional destructive action (e.g. bulk delete on the Research tab).
  // Rendered as a left-aligned ghost button styled in red.
  dangerLabel, onDanger, dangerIcon,
}) {
  if (count === 0) return null;
  return (
    <div className="selbar">
      <span className="selbar-count">
        <span className="selbar-n">{count}</span> of {total} ads selected
      </span>
      <button className="selbar-ghost" onClick={onClear}>Clear</button>
      <button className="selbar-ghost" onClick={onSelectAll}>Select all</button>
      {dangerLabel && (
        <button
          className="selbar-ghost"
          onClick={onDanger}
          style={{ color: 'var(--danger, #c0392b)', borderColor: 'var(--danger, #c0392b)' }}
        >
          <Icon name={dangerIcon || 'x'} size={14} />
          {dangerLabel}
        </button>
      )}
      <div className="selbar-spacer" />
      {secondaryLabel && (
        <button className="selbar-secondary" onClick={onSecondary}>
          {secondaryLabel}
          <Icon name={secondaryIcon || 'arrowRight'} size={14} />
        </button>
      )}
      <button className="selbar-primary" onClick={onCTA}>
        {ctaLabel}
        <Icon name={icon || 'arrowRight'} size={14} />
        <kbd className="selbar-kbd">⌘↵</kbd>
      </button>
    </div>
  );
};

window.TranscriptCard = function TranscriptCard({
  ad, script, selected, onToggle,
  // Edit support: when ``editable`` is true the card surfaces an Edit button.
  // ``rawText`` is the unparsed response_text used as the initial textarea
  // value; ``onSave(newText)`` is called with the user's edits.
  editable, rawText, onSave,
  onRegenerate, onDiscard, onPromote, promotedAt,
}) {
  const p = PLATFORMS[ad.platform] || PLATFORMS.foreplay;
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const transcriptText = ad.transcriptRaw
    || (Array.isArray(ad.transcript)
      ? ad.transcript.map(seg => seg.body || seg.t || '').filter(Boolean).join('\n')
      : (ad.transcript || ''));
  const startEdit = () => {
    setDraft(rawText || script.map(l => l.body).join('\n\n'));
    setEditing(true);
  };
  const cancelEdit = () => { setEditing(false); setDraft(''); };
  const saveEdit = async () => {
    if (!onSave) return;
    setSaving(true);
    try {
      await onSave(draft);
      setEditing(false);
    } finally {
      setSaving(false);
    }
  };
  return (
    <div className={`transcript ${selected ? 'sel' : ''}`}>
      <header className="t-hdr">
        <div className={`t-cbx ${selected ? 'on' : ''}`} onClick={onToggle}>
          {selected && <Icon name="check" size={10} />}
        </div>
        <span className="t-brand">{ad.brand}</span>
        <span className="ad-plat" style={{ background: p.bg, color: p.color }}>
          <span className="ad-plat-dot" style={{ background: p.color }} />
          {p.label}
        </span>
        <span className="t-meta">{ad.id} · remodeled just now</span>
        <div className="t-hdr-spacer" />
        {editable && !editing && (
          <button className="t-edit-btn" onClick={startEdit} title="Edit this script">
            <Icon name="edit" size={12} /> Edit
          </button>
        )}
        {editable && !editing && onRegenerate && (
          <button className="t-edit-btn" onClick={onRegenerate} title="Regenerate this script">
            <Icon name="loader" size={12} /> Regenerate
          </button>
        )}
        {editable && !editing && onDiscard && (
          <button className="t-edit-btn ghost" onClick={onDiscard} title="Discard this script">
            <Icon name="trash" size={12} /> Discard
          </button>
        )}
        {editable && !editing && onPromote && (
          <button className="t-edit-btn primary" onClick={onPromote} title="Promote this script to the video queue">
            <Icon name="film" size={12} /> {promotedAt ? 'Promoted' : 'Promote to Video Queue'}
          </button>
        )}
        {editing && (
          <>
            <button className="t-edit-btn ghost" onClick={cancelEdit} disabled={saving}>
              Cancel
            </button>
            <button className="t-edit-btn primary" onClick={saveEdit} disabled={saving || !draft.trim()}>
              {saving ? 'Saving…' : 'Save'}
            </button>
          </>
        )}
      </header>
      <div style={{ padding: '8px 14px 0', color: 'var(--fg-3)', fontSize: 12, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        {typeof ad.score === 'number' && <span>Score {ad.score.toFixed ? ad.score.toFixed(1) : ad.score}</span>}
        {ad.daysRunning ? <span>{ad.daysRunning}d running</span> : null}
        {ad.directionLabel ? <span>{ad.directionLabel}</span> : null}
        {promotedAt ? <span>Promoted {String(promotedAt).slice(0, 16)}</span> : null}
      </div>
      {(transcriptText || ad.reasoning) && (
        <details style={{ margin: '8px 14px 0', border: '1px solid var(--border-subtle)', borderRadius: 8, padding: '8px 10px', background: 'var(--bg-sunken)' }}>
          <summary style={{ cursor: 'pointer', fontSize: 12, color: 'var(--fg-2)' }}>Original transcript and scoring notes</summary>
          {ad.reasoning && <p style={{ margin: '8px 0', fontSize: 12, color: 'var(--fg-2)' }}>{ad.reasoning}</p>}
          {transcriptText && <pre style={{ whiteSpace: 'pre-wrap', maxHeight: 220, overflow: 'auto', fontSize: 12, lineHeight: 1.45 }}>{transcriptText}</pre>}
        </details>
      )}
      {editing ? (
        <textarea
          className="t-edit-area"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          spellCheck
          autoFocus
        />
      ) : (
        <div className="t-script">
          {script.map((line, i) => (
            <div key={i} className="t-line">
              {line.tag ? <span className="t-tag">{line.tag}</span> : null}
              <span>{line.body}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
