/**
 * A concept video, as a browsable card.
 *
 * Concepts are market education — someone scans the shelf and picks what they
 * need — so this is a poster-led grid tile. The platform track is a course you
 * work through in order and is rendered as a list instead; see
 * `LearnWalkthroughList`.
 */
import { formatLearnDuration } from '@pig/core';
import { Badge, Card } from '@/components/ui';
import { ArchiveControl } from './ArchiveControl';
import { learnPlayback } from './model';
import { LearnPoster } from './LearnPoster';
import type { LearnResourceView } from './model';

export function LearnVideoCard({
  resource,
  managing,
  onPlay,
}: {
  resource: LearnResourceView;
  managing: boolean;
  onPlay: (resource: LearnResourceView) => void;
}) {
  const playback = learnPlayback(resource);
  return (
    <Card className="group relative flex min-w-0 flex-col overflow-hidden transition-shadow duration-1 ease-enter hover:shadow-md">
      <button
        type="button"
        onClick={() => onPlay(resource)}
        // The ring is inset because the card clips its overflow, and an offset
        // ring on a clipped child is a focus indicator nobody can see.
        className="flex min-w-0 flex-1 flex-col text-left focus-visible:ring-inset focus-visible:ring-offset-0"
      >
        <LearnPoster
          seed={resource.id}
          track={resource.track}
          duration={formatLearnDuration(resource.durationSeconds)}
          // Only a PIG-hosted clip has a real frame; a Cap embed resolves to
          // an iframe and falls back to the generated poster.
          poster={playback?.kind === 'video' ? playback.poster : null}
          alt={`Still from ${resource.title}`}
        />
        <div className="flex min-w-0 flex-1 flex-col gap-1.5 p-4">
          {/* break-words, not truncate: a title is the only way to tell two
              walkthroughs apart, and an unbroken word at 393px is what drags
              the whole page sideways. */}
          <h3 className="min-w-0 break-words font-semibold leading-snug">{resource.title}</h3>
          {resource.summary ? (
            <p className="line-clamp-2 min-w-0 break-words text-sm leading-6 text-muted">
              {resource.summary}
            </p>
          ) : null}
        </div>
      </button>

      {managing ? (
        <div className="pointer-events-none absolute inset-x-0 top-0 flex min-w-0 items-start justify-between gap-2 p-2">
          <Badge
            tone={resource.visibility === 'code' ? 'accent' : 'neutral'}
            className="pointer-events-auto bg-surface/90 backdrop-blur-sm"
          >
            {resource.visibility === 'code' ? 'Shared by code' : 'Members only'}
          </Badge>
          <ArchiveControl
            id={resource.id}
            title={resource.title}
            className="pointer-events-auto"
          />
        </div>
      ) : null}
    </Card>
  );
}
