'use client';

/**
 * ModuleCard — shared presentation card used by both Palette and Canvas.
 *
 * Shows the module label (from module_labels i18n), category badge,
 * shared/this-device-only badge, and an optional edit button.
 *
 * All styling is token-only. All interactives are real <button> elements.
 */

import { Pencil } from 'lucide-react';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Badge } from '@/components/ui/primitives/Badge';
import type { LayoutModule } from '@/server/page-layout/types';
import { KNOWN_LABEL_KEYS } from './Palette';

export interface ModuleCardProps {
  /** The layout module instance to display. */
  module: LayoutModule;
  /**
   * When provided, controls which badge is shown:
   * - `true`  → "Shared" badge (same instanceId in both device arrays)
   * - `false` → "This device only" badge
   * - `undefined` → no badge
   */
  showShared?: boolean;
  /** When provided, renders an edit button and calls this on click. */
  onEdit?: () => void;
  /** When true, show the grab handle affordance (decorative, drag listeners live on the li). */
  showHandle?: boolean;
}

/** Derive category from module type string. */
function categoryFromType(
  type: string,
): 'deal-row' | 'banner' | 'vendor-spotlight' | 'static' | 'custom' {
  if (type.startsWith('deal-row:')) return 'deal-row';
  if (type === 'banner' || type.startsWith('banner:')) return 'banner';
  if (type === 'vendor-spotlight' || type.startsWith('vendor-spotlight:'))
    return 'vendor-spotlight';
  if (type === 'static-content' || type.startsWith('static-content:')) return 'static';
  return 'custom';
}

/** Badge tone per category. */
const CATEGORY_TONE: Record<
  'deal-row' | 'banner' | 'vendor-spotlight' | 'static' | 'custom',
  'brand' | 'success' | 'neutral'
> = {
  'deal-row': 'brand',
  banner: 'success',
  'vendor-spotlight': 'neutral',
  static: 'neutral',
  custom: 'neutral',
};

export function ModuleCard({ module, showShared, onEdit, showHandle }: ModuleCardProps) {
  const tLabels = useT('module_labels');
  const tOrg = useT('page_organizer');

  const category = categoryFromType(module.type);

  // Safe label lookup — fall back to type string if key not in registry
  const label =
    module.type in KNOWN_LABEL_KEYS
      ? tLabels(module.type as Parameters<typeof tLabels>[0])
      : module.type;

  // module_categories is a nested object — access via t key
  const categoryLabels = tOrg('module_categories' as Parameters<typeof tOrg>[0]) as unknown as {
    deal_row: string;
    banner: string;
    vendor_spotlight: string;
    static: string;
    custom: string;
  };
  const catLabelKey: keyof typeof categoryLabels =
    category === 'deal-row'
      ? 'deal_row'
      : category === 'vendor-spotlight'
        ? 'vendor_spotlight'
        : category;
  const catLabel = categoryLabels[catLabelKey];

  // For `deal-row:auto-scroll`, override the category badge with the specific
  // module label so it's visually distinct from generic "deal-row" rows.
  const catBadgeLabel = module.type === 'deal-row:auto-scroll' ? label : catLabel;

  // For `deal-row:category` instances, append the selected category name
  // (e.g. "Category: Beverages") so admins can distinguish multiple category rows.
  let displayLabel = label;
  if (module.type === 'deal-row:category') {
    const cfg = module.config as { categoryName?: { he?: string; en?: string } } | undefined;
    const name = cfg?.categoryName?.he;
    if (name) displayLabel = `${label}: ${name}`;
  }

  return (
    <div
      className="bg-surface-base border-border-default flex items-center gap-3 rounded-md border px-3 py-2"
      data-module-type={module.type}
    >
      {/* Drag handle area — decorative; pointer events via SortableItem listeners on the li */}
      {showHandle && (
        <span
          aria-hidden="true"
          className="text-text-muted shrink-0 cursor-grab text-sm select-none active:cursor-grabbing"
        >
          ⠿
        </span>
      )}

      {/* Label + badges */}
      <div className="flex min-w-0 flex-1 flex-col gap-1">
        <span className="text-text-primary truncate text-sm font-medium">{displayLabel}</span>
        <div className="flex flex-wrap gap-1">
          {/* Category badge */}
          <Badge tone={CATEGORY_TONE[category]} size="sm">
            {catBadgeLabel}
          </Badge>
          {/* Shared / this-device-only badge */}
          {showShared !== undefined && (
            <Badge tone="neutral" size="sm">
              {showShared ? tOrg('shared_badge') : tOrg('this_device_only_badge')}
            </Badge>
          )}
        </div>
      </div>

      {/* Edit button — must stop pointer propagation to not trigger drag */}
      {onEdit && (
        <Button
          variant="ghost"
          size="sm"
          aria-label={`${label} — ${tOrg('config_heading')}`}
          onClick={(e) => {
            e.stopPropagation();
            onEdit();
          }}
          onPointerDown={(e) => e.stopPropagation()}
        >
          <Pencil size={14} aria-hidden="true" />
        </Button>
      )}
    </div>
  );
}
