'use client';

/* EngagementProfileHeader — phase 08 (D-05, D-06, D-07).
 * Purpose: Identity header card — avatar (photo or initials), display name, jobTitle,
 *          department, email mailto: link, and last-active row.
 * Avatar: photo from /api/mobile/engagement/user/[userId]/photo; on error → initials.
 * Last-active: relative (≤7d via date-fns) or absolute (>7d via formatInUserTimezone). */

import { useState } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { Card, CardContent } from '@/components/ui/card';
import { getInitials } from '@/components/mobile/EngagementUserRow';
import { useUserTimezone, formatInUserTimezone } from '@/lib/hooks/use-user-timezone';

export interface EngagementProfileHeaderProps {
  displayName: string;
  email: string;
  jobTitle: string | null;
  department: string | null;
  // Last-active source: caller derives from response (most recent of recentEntries[0].entry_date,
  // or the most-recent snapshots[].period_end). null if no signal at all.
  lastActiveAt: string | null;  // ISO date string or null (D-06)
  // Used to build the photo URL — userId is the same value as the route segment
  userId: string;
}

export function EngagementProfileHeader({
  displayName,
  email,
  jobTitle,
  department,
  lastActiveAt,
  userId,
}: EngagementProfileHeaderProps) {
  const [photoFailed, setPhotoFailed] = useState(false);
  const tz = useUserTimezone();

  // Compute last-active label (D-06)
  let lastActiveLabel: string | null = null;
  if (lastActiveAt) {
    const ms = Date.now() - new Date(lastActiveAt).getTime();
    if (ms <= 7 * 24 * 60 * 60 * 1000) {
      // Relative — ≤7d
      lastActiveLabel = `Active ${formatDistanceToNow(new Date(lastActiveAt), { addSuffix: true })}`;
    } else {
      // Absolute — >7d
      const formatted = formatInUserTimezone(lastActiveAt, tz, { month: 'short', day: 'numeric', year: 'numeric' });
      lastActiveLabel = `Last active ${formatted}`;
    }
  }

  return (
    <Card className="py-0 shadow-none">
      <CardContent className="px-4 py-4 flex items-center gap-3">
        {/* Avatar — photo or initials fallback */}
        {!photoFailed ? (
          <img
            src={`/api/mobile/engagement/user/${userId}/photo`}
            alt={displayName}
            className="h-14 w-14 rounded-full object-cover shrink-0"
            onError={() => setPhotoFailed(true)}
          />
        ) : (
          <span
            aria-hidden="true"
            className="h-14 w-14 rounded-full bg-muted flex items-center justify-center shrink-0 text-xs font-semibold text-foreground"
          >
            {getInitials(displayName)}
          </span>
        )}

        {/* Identity stack */}
        <div className="flex-1 min-w-0 space-y-1">
          <p className="text-xl font-semibold truncate">{displayName}</p>
          {jobTitle && (
            <p className="text-xs text-muted-foreground truncate">{jobTitle}</p>
          )}
          {department && (
            <p className="text-xs text-muted-foreground truncate">{department}</p>
          )}
          <a
            href={`mailto:${email}`}
            className="text-sm text-primary underline-offset-4 hover:underline truncate block min-h-[44px] flex items-center"
          >
            {email}
          </a>
          {lastActiveLabel && (
            <p className="text-xs text-muted-foreground">{lastActiveLabel}</p>
          )}
        </div>
      </CardContent>
    </Card>
  );
}
