'use client';

import KindChip from '@/app/components/ui/marketplace/kind-chip.jsx';
import KindBadge from '@/app/components/ui/marketplace/kind-badge.jsx';
import InstallToggle from '@/app/components/ui/marketplace/install-toggle.jsx';

const STAGE_KIND_LABEL = {
  intake_form: 'intake',
  agent_run: 'agent',
  policy_gate: 'policy',
  human_approval: 'approval',
  package: 'package',
};

function summarizeStages(stageKinds) {
  if (!Array.isArray(stageKinds) || !stageKinds.length) return '—';
  return stageKinds.map((kind) => STAGE_KIND_LABEL[kind] || kind).join(' → ');
}

/**
 * Marketplace card for `kind:'workflow'`. Install writes a process_definitions
 * row via the same server action that handles every other kind (toggleInstallAction
 * → setItemInstalled → upsertDefinition). Uninstall soft-archives the definition
 * if no cases are in flight.
 *
 * The card surfaces the stage shape so an operator can see what they're installing
 * before clicking — important for workflows because installation writes data the
 * engine will execute when cases are started.
 *
 * @param {{
 *   item: any,
 *   toggleAction: any,
 *   currentKind?: string,
 * }} props
 */
export default function WorkflowCard({ item, toggleAction, currentKind }) {
  const installed = Boolean(item.installed);
  const workflow = item.workflow || {};

  return (
    <li className={`mkt-card kind-workflow ${installed ? 'on' : ''}`}>
      <div className="mkt-card-head">
        <KindChip kind="workflow" size={20} />
        <KindBadge kind="workflow" />
      </div>

      <div className="mkt-card-body">
        <h3 className="mkt-card-title">{item.slug}</h3>
        <p className="mkt-card-desc">{item.description}</p>
      </div>

      <div className="mkt-card-meta">
        <span>Stages <b>{workflow.stage_count || 0}</b></span>
        <span>Shape <b>{summarizeStages(workflow.stage_kinds)}</b></span>
        <span>By <b>{item.author}</b></span>
        {item.version ? <span>Version <b>{item.version}</b></span> : null}
        {item.risk_summary ? (
          <span>Risk <b>{item.risk_summary.length > 60 ? `${item.risk_summary.slice(0, 60)}…` : item.risk_summary}</b></span>
        ) : null}
      </div>

      <div className="mkt-card-foot">
        <span className={`mkt-availability ${installed ? 'installed' : ''}`}>
          {installed ? 'Installed' : 'Available'}
        </span>
        <InstallToggle
          action={toggleAction}
          itemId={item.id}
          installed={installed}
          available={true}
          label={`${installed ? 'Uninstall' : 'Install'} ${item.slug}`}
          slugHint={item.slug}
          currentKind={currentKind}
        />
      </div>
    </li>
  );
}
