// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * Right-hand visitor context pane — Intercom / Zendesk / Gorgias convention.
 * Holds everything the operator needs without leaving the transcript:
 * identity, session timeline, device, geo, cart value, page trail.
 */

import { Globe, Monitor, Smartphone, Tablet, MapPin, ShoppingCart, Repeat, Sparkles, Link as LinkIcon } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { ConversationDetail as ConvDetail } from '../lib/types';
import { VisitorAvatar } from './VisitorAvatar';
import { CapturedContactBlock } from './CapturedContactBlock';

interface VisitorContextPanelProps {
  conversation: ConvDetail;
}

function DeviceIcon({ device }: { device: ConvDetail['device'] }) {
  if (device === 'mobile') return <Smartphone size={14} />;
  if (device === 'tablet') return <Tablet size={14} />;
  return <Monitor size={14} />;
}

function relativeDate(date: Date | string, locale: string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  const diffMs = Date.now() - d.getTime();
  const minutes = Math.floor(diffMs / 60_000);
  if (minutes < 60) return locale === 'de' ? `vor ${minutes} Min.` : `${minutes} min ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return locale === 'de' ? `vor ${hours} Std.` : `${hours} h ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return locale === 'de' ? `vor ${days} Tagen` : `${days} d ago`;
  const months = Math.floor(days / 30);
  return locale === 'de' ? `vor ${months} Mon.` : `${months} mo ago`;
}

function formatMoney(cents: number, currency: string, locale: string): string {
  return new Intl.NumberFormat(locale === 'de' ? 'de-DE' : 'en-GB', { style: 'currency', currency }).format(cents / 100);
}

export function VisitorContextPanel({ conversation }: VisitorContextPanelProps) {
  const { t, locale } = useTranslation();
  const pages = conversation.pageTrail.map((v) => v.url);

  return (
    <aside
      className="w-full border-l border-gray-200 bg-white overflow-y-auto"
      data-testid="visitor-context-panel"
    >
      <div className="p-5 border-b border-gray-100">
        <div className="flex items-center gap-3 mb-3">
          <VisitorAvatar handle={conversation.visitorRef} size="lg" />
          <div className="min-w-0">
            <div className="font-semibold text-gray-900 truncate">{conversation.visitorRef}</div>
            <div className="text-xs text-gray-500 flex items-center gap-1">
              {conversation.isReturning ? (
                <>
                  <Repeat size={11} className="text-violet-500" />
                  {t('conversations.visitor.returning')}
                </>
              ) : (
                <>
                  <Sparkles size={11} className="text-emerald-500" />
                  {t('conversations.visitor.firstTime')}
                </>
              )}
            </div>
          </div>
        </div>

        {conversation.cartValueCents !== null && conversation.cartCurrency && (
          <div className="rounded-md bg-emerald-50 border border-emerald-200 px-3 py-2 mb-3" data-testid="cart-value">
            <div className="flex items-center gap-1.5 text-xs text-emerald-700 font-semibold mb-0.5">
              <ShoppingCart size={12} />
              {t('conversations.visitor.activeCart')}
            </div>
            <div className="text-base font-bold text-emerald-800">
              {formatMoney(conversation.cartValueCents, conversation.cartCurrency, locale)}
            </div>
          </div>
        )}
      </div>

      <CapturedContactBlock conversationId={conversation.id} />

      <Section title={t('conversations.visitor.session')}>
        <Row label={t('conversations.visitor.firstSeen')} value={relativeDate(conversation.visitorFirstSeenAt, locale)} />
        <Row label={t('conversations.visitor.startedSession')} value={relativeDate(conversation.startedAt, locale)} />
        <Row label={t('conversations.visitor.locale')} value={conversation.visitorLocale.toUpperCase()} />
        <Row
          label={t('conversations.visitor.country')}
          value={
            <span className="inline-flex items-center gap-1">
              <MapPin size={11} className="text-gray-400" />
              {conversation.country}
            </span>
          }
        />
        <Row
          label={t('conversations.visitor.device')}
          value={
            <span className="inline-flex items-center gap-1">
              <DeviceIcon device={conversation.device} />
              {conversation.browser}
            </span>
          }
        />
        <Row
          label={t('conversations.visitor.referrer')}
          value={
            <span className="inline-flex items-center gap-1">
              <Globe size={11} className="text-gray-400" />
              {conversation.referrer}
            </span>
          }
        />
      </Section>

      <Section title={t('conversations.visitor.pageTrail')}>
        {pages.length === 0 ? (
          <p className="text-xs text-gray-400">—</p>
        ) : (
          <ol className="space-y-1.5">
            {pages.map((url, idx) => {
              const isLast = idx === pages.length - 1;
              try {
                const u = new URL(url);
                const path = u.pathname || '/';
                return (
                  <li key={`${url}-${idx}`} className="flex items-start gap-2 text-xs">
                    <span
                      className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-[10px] font-bold shrink-0 ${
                        isLast ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-600'
                      }`}
                    >
                      {idx + 1}
                    </span>
                    <span className="min-w-0">
                      <span className="block font-medium text-gray-900 truncate">{path}</span>
                      <span className="block text-gray-400 truncate">{u.host}</span>
                    </span>
                  </li>
                );
              } catch {
                return (
                  <li key={`${url}-${idx}`} className="flex items-center gap-2 text-xs text-gray-700">
                    <LinkIcon size={10} />
                    <span className="truncate">{url}</span>
                  </li>
                );
              }
            })}
          </ol>
        )}
      </Section>

      <Section title={t('conversations.visitor.messageBreakdown')}>
        <Row label={t('conversations.visitor.byVisitor')} value={String(conversation.userMessageCount)} />
        <Row label={t('conversations.visitor.byAssistant')} value={String(conversation.assistantMessageCount)} />
        <Row label={t('conversations.visitor.byOperator')} value={String(conversation.operatorMessageCount)} />
      </Section>
    </aside>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="px-5 py-4 border-b border-gray-100">
      <h3 className="text-[10px] uppercase font-bold tracking-wider text-gray-400 mb-2">{title}</h3>
      <div className="space-y-1.5">{children}</div>
    </div>
  );
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between gap-2 text-xs">
      <span className="text-gray-500 shrink-0">{label}</span>
      <span className="text-gray-900 font-medium text-right truncate">{value}</span>
    </div>
  );
}
