'use client';

import { motion } from 'motion/react';
import { useMemo, useState, useEffect } from 'react';
import { evaluateOpeningStatus, resolveRestaurantTimezone } from '@/lib/opening-hours';
import { getLieferandoAffiliateUrl } from '@/lib/affiliate';
import { formatCuisineDisplay } from '@/lib/cuisine';
import { normalizeAddressDisplay, capitalizeCity } from '@/lib/format-address';
import { useTranslation } from '@/lib/i18n/context';
import { shareViaNativeOrWeb } from '@/lib/share';
import type { RankingEntry } from '@/lib/ranking';

interface MatchResultProps {
  restaurantId?: number | string;
  restaurantName: string;
  matchPercentage: number;
  imageUrl?: string;
  isSymbolImage?: boolean;
  address?: string;
  city?: string;
  postalCode?: string;
  suburb?: string;
  phone?: string;
  website?: string;
  reservationUrl?: string;
  lieferandoUrl?: string;
  openingHoursRaw?: string;
  cuisine?: string;
  lat?: number;
  lon?: number;
  mapsUrl: string;
  isJokerResult?: boolean;
  isForcedChoice?: boolean;
  sessionCode?: string;
  runnerUps?: RankingEntry[];
  activeParticipantCount?: number;
  yesCount?: number;
  poolCount?: number;
  onLeaveSession: () => void;
  onNewTable: () => void;
}

type ClickType = 'maps' | 'call' | 'reservation' | 'order' | 'share' | 'website';

function trackOutboundClick(sessionCode: string | undefined, restaurantId: number | string | undefined, clickType: ClickType) {
  if (!sessionCode) return;
  const payload = JSON.stringify({ sessionCode, restaurantId, clickType });
  try {
    if (navigator.sendBeacon) {
      const blob = new Blob([payload], { type: 'application/json' });
      navigator.sendBeacon('/api/track', blob);
    } else {
      fetch('/api/track', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: payload,
        keepalive: true,
      }).catch(() => {});
    }
  } catch {
    // Tracking ist rein informativ - niemals den Nutzerfluss stoeren.
  }
}

// Reines CSS-Konfetti (Keyframes in app/globals.css), kein externes Paket.
// Wird nur fuer echte Matches gerendert (nicht fuer den Joker).
function ConfettiBurst() {
  const pieces = useMemo(
    () =>
      Array.from({ length: 42 }).map((_, i) => ({
        left: Math.random() * 100,
        delay: Math.random() * 0.35,
        duration: 2.4 + Math.random() * 1.4,
        color: ['#fe3c72', '#00c2a8', '#fbbf24', '#ffffff', '#a78bfa'][i % 5],
        width: 6 + Math.random() * 5,
        height: 10 + Math.random() * 6,
        rotate: Math.random() * 360,
      })),
    []
  );

  return (
    <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
      {pieces.map((p, i) => (
        <span
          key={i}
          className="confetti-piece rounded-sm"
          style={{
            left: `${p.left}%`,
            width: p.width,
            height: p.height,
            backgroundColor: p.color,
            animationDelay: `${p.delay}s`,
            animationDuration: `${p.duration}s`,
            transform: `rotate(${p.rotate}deg)`,
          }}
        />
      ))}
    </div>
  );
}

// Vollbild-Ergebnis-Screen fuer Match UND Joker (ersetzt das fruehere Modal).
// Scrollbarer Inhalt (Stempel, Siegerkarte, Runner-ups, Datenhinweis) plus
// fixe Bottom-Bar mit "Neuen Tisch starten" und "Tisch verlassen".
export function MatchResult({
  restaurantId, restaurantName, matchPercentage, imageUrl, isSymbolImage,
  address, city, postalCode, suburb, phone, website, reservationUrl, lieferandoUrl, openingHoursRaw,
  cuisine, lat, lon, mapsUrl, isJokerResult, isForcedChoice,
  sessionCode, runnerUps, activeParticipantCount, yesCount, poolCount,
  onLeaveSession, onNewTable,
}: MatchResultProps) {
  const { t, locale } = useTranslation();
  const tz = resolveRestaurantTimezone(lat, lon);
  const opening = evaluateOpeningStatus(openingHoursRaw, new Date(), tz, t.openingHours);
  const [imgBroken, setImgBroken] = useState(false);

  useEffect(() => {
    setImgBroken(false);
  }, [imageUrl]);

  const roundedPct = Math.round(matchPercentage);

  const quote = useMemo(() => {
    if (isForcedChoice) {
      const quotes = t.match.forcedChoiceQuotes;
      return quotes[Math.floor(Math.random() * quotes.length)];
    }
    if (isJokerResult) {
      const options = t.match.buildPartialQuotes(roundedPct);
      return options[Math.floor(Math.random() * options.length)];
    }
    return null;
    // eslint-disable-next-line react-hooks/exhaustive-deps -- bewusst nur einmal pro Mount
  }, []);

  // Lieferando/Bestellen ist derzeit bewusst DEAKTIVIERT (nicht gerendert),
  // die Affiliate-/Tracking-Logik bleibt aber erhalten.
  const orderUrl = getLieferandoAffiliateUrl({
    restaurantId,
    name: restaurantName,
    city,
    lieferandoUrl,
  });

  const cuisineLabels = formatCuisineDisplay(cuisine, locale);
  const displayAddress = normalizeAddressDisplay(address, postalCode, city, suburb);

  const callHref = phone
    ? `tel:${phone.replace(/\s/g, '')}`
    : reservationUrl || website || '#';
  const callTarget = phone ? undefined : '_blank';
  const callType: ClickType = phone ? 'call' : reservationUrl ? 'reservation' : 'website';

  async function handleShareResult() {
    trackOutboundClick(sessionCode, restaurantId, 'share');
    await shareViaNativeOrWeb({
      title: restaurantName,
      text: t.match.shareResultText(restaurantName),
      url: mapsUrl,
    });
  }

  const stampColor = isJokerResult
    ? 'border-amber-400 text-amber-400'
    : 'border-yumder-pink text-yumder-pink';

  return (
    <main className="relative flex flex-col h-dvh bg-neutral-950 safe-top">
      {!isJokerResult && <ConfettiBurst />}

      <div className="relative z-10 flex-1 min-h-0 overflow-y-auto no-scrollbar px-4 pb-5 space-y-3.5 pt-5">
        {/* Stempel */}
        <div className="flex justify-center pt-2 pb-1">
          <div className={`border-[2.5px] ${stampColor} font-black text-2xl tracking-wider px-5 py-1 rounded-2xl transform -rotate-3 select-none uppercase`}>
            {isJokerResult ? t.match.jokerLabel : t.match.matchLabel}
          </div>
        </div>

        {/* Joker-Spruch als Ueberschrift (ueber der Karte) */}
        {isJokerResult && quote && (
          <div className="text-center px-2 pt-1 pb-0.5">
            <h2 className="text-sm font-black text-amber-300 leading-snug tracking-tight">{quote}</h2>
          </div>
        )}

        {/* Sieger-Karte */}
        <article className="bg-neutral-900 rounded-3xl border border-white/10 overflow-hidden shadow-xl">
          {isJokerResult && (
            <div className="h-1 w-full bg-gradient-to-r from-amber-400 via-amber-200 to-amber-500" />
          )}
          <div className="h-40 w-full relative bg-neutral-800">
            {imageUrl && !imgBroken ? (
              <img
                src={imageUrl}
                alt=""
                className="w-full h-full object-cover"
                draggable={false}
                onError={() => setImgBroken(true)}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center text-neutral-500 text-sm text-center px-6">
                {t.swipeCard.noImageAvailable}
              </div>
            )}
            {isSymbolImage && (
              <span className="absolute top-2 right-2 bg-black text-xs px-2 py-1 rounded">{t.swipeCard.symbolBadge}</span>
            )}
            {opening.isOpen !== null && (
              <div className="absolute top-3 left-3 bg-neutral-950 px-3 py-1 rounded-full border border-white/10 shadow-md">
                <span className={`text-xs font-bold ${opening.isOpen ? 'text-yumder-teal' : 'text-rose-400'}`}>
                  {opening.label}
                </span>
              </div>
            )}
          </div>

          <div className="p-4 space-y-3">
            <div>
              <div className="flex items-start justify-between gap-2">
                <h1 className="text-xl font-extrabold text-white tracking-tight leading-snug">{restaurantName}</h1>
                {isJokerResult ? (
                  <span className="text-xs font-extrabold text-amber-300 bg-neutral-800 px-2.5 py-1 rounded-lg border border-amber-500/40 shrink-0">
                    {t.match.chosenByJoker}
                  </span>
                ) : (
                  <span className="text-xs font-bold text-neutral-200 bg-neutral-800 px-2.5 py-1 rounded-lg border border-white/10 shrink-0">
                    {t.match.votesResult(yesCount ?? 0, activeParticipantCount ?? 0)}
                  </span>
                )}
              </div>

              {isJokerResult && typeof poolCount === 'number' && poolCount > 0 && (
                <p className="text-[11px] text-neutral-400 font-medium mt-1">
                  {t.match.selectedFromUndecided(poolCount)}
                </p>
              )}

              {displayAddress && (
                <p className="text-xs text-neutral-300 font-medium mt-1.5 flex items-center gap-1.5">
                  <svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-yumder-pink shrink-0" fill="currentColor" aria-hidden="true">
                    <path d="M12 21s-7-5.5-7-11a7 7 0 0 1 14 0c0 5.5-7 11-7 11zm0-9.5A1.75 1.75 0 1 0 12 8a1.75 1.75 0 0 0 0 3.5z" />
                  </svg>
                  <span>{displayAddress}</span>
                </p>
              )}
            </div>

            {cuisineLabels.length > 0 && (
              <div className="flex flex-wrap gap-1.5 pt-0.5">
                {cuisineLabels.map((label) => (
                  <span key={label} className="px-3.5 py-1 rounded-full text-xs font-extrabold bg-yumder-pink text-white">
                    {label}
                  </span>
                ))}
              </div>
            )}

            {/* Aktionen */}
            <div className="pt-1.5 space-y-2">
              <a
                href={callHref}
                target={callTarget}
                rel={callTarget ? 'noreferrer noopener' : undefined}
                onClick={() => trackOutboundClick(sessionCode, restaurantId, callType)}
                className="w-full py-3 px-4 bg-yumder-teal hover:bg-teal-400 text-neutral-900 font-bold text-sm rounded-2xl flex items-center justify-center gap-2 active:scale-[0.98] transition-all"
              >
                <svg viewBox="0 0 24 24" className="w-4 h-4" fill="currentColor" aria-hidden="true">
                  <path d="M6 2h4l2 5-2.5 1.5a11 11 0 0 0 5 5L16 11l5 2v4a2 2 0 0 1-2 2C10.5 19 5 13.5 5 4a2 2 0 0 1 1-2z" />
                </svg>
                {t.match.callOrReserveButton}
              </a>

              <div className="grid grid-cols-2 gap-2">
                <a
                  href={mapsUrl}
                  target="_blank"
                  rel="noreferrer noopener"
                  onClick={() => trackOutboundClick(sessionCode, restaurantId, 'maps')}
                  className="py-2.5 px-3 bg-yumder-pink hover:bg-pink-500 text-white font-bold text-xs rounded-2xl flex items-center justify-center gap-2 active:scale-[0.98] transition-all"
                >
                  <svg viewBox="0 0 24 24" className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                    <path d="M12 21s-7-5.5-7-11a7 7 0 0 1 14 0c0 5.5-7 11-7 11z" strokeLinecap="round" strokeLinejoin="round" />
                    <circle cx="12" cy="10" r="2.5" />
                  </svg>
                  {t.match.mapsButton}
                </a>
                <button
                  onClick={handleShareResult}
                  className="py-2.5 px-3 bg-neutral-800 hover:bg-neutral-700 text-neutral-100 font-bold text-xs rounded-2xl border border-white/10 flex items-center justify-center gap-2 active:scale-[0.98] transition-all"
                >
                  <svg viewBox="0 0 24 24" className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                  </svg>
                  {t.match.shareResultButton}
                </button>
              </div>
            </div>
          </div>
        </article>

        {/* Datenhinweis */}
        <div className="bg-neutral-800 border border-white/10 rounded-2xl p-3 flex items-start gap-2.5">
          <svg viewBox="0 0 24 24" className="w-4 h-4 text-yumder-teal mt-0.5 shrink-0" fill="currentColor" aria-hidden="true">
            <path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z" />
          </svg>
          <p className="text-xs text-neutral-300 font-medium leading-relaxed">{t.match.dataDisclaimer}</p>
        </div>

        {/* Runner-ups (nur echtes Match, ab 3 Teilnehmern) */}
        {!isJokerResult && (activeParticipantCount ?? 0) >= 3 && runnerUps && runnerUps.length > 0 && (
          <section className="space-y-2.5 pt-0.5">
            <h2 className="text-xs font-bold uppercase tracking-wider text-neutral-400 px-1">
              {t.match.runnerUpsTitle}
            </h2>
            <div className="space-y-2.5">
              {runnerUps.slice(0, 2).map((ru) => {
                const ruImage = ru.sponsor_image_url || ru.osm_image_url || ru.admin_image_url || ru.fallback_image_url;
                const ruStreet = ru.address ? ru.address.split(',')[0].trim() : '';
                const ruCity = city ? capitalizeCity(city.trim()) : '';
                const ruSuburb = ru.suburb ? capitalizeCity(ru.suburb.trim()) : '';
                const ruCityLine = [ru.postal_code, ruCity].filter(Boolean).join(' ');
                const ruCityWithSuburb = ruSuburb ? `${ruCityLine} (${ruSuburb})` : ruCityLine;
                const ruCuisine = formatCuisineDisplay(ru.cuisine, locale);
                const ruMapsUrl = `https://www.google.com/maps/search/${encodeURIComponent(
                  (ru.name || '') + ' ' + (ru.address || '')
                )}`;
                return (
                  <div key={ru.restaurant_id} className="p-3.5 bg-neutral-900 rounded-2xl border border-white/10 space-y-2.5">
                    <div className="flex items-center justify-between gap-3">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-12 h-12 rounded-xl overflow-hidden bg-neutral-800 shrink-0">
                          {ruImage ? (
                            <img src={ruImage} alt="" className="w-full h-full object-cover" draggable={false} />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-neutral-500 text-[10px] text-center px-1">
                              {t.swipeCard.noImageAvailable}
                            </div>
                          )}
                        </div>
                        <div className="min-w-0">
                          <h3 className="text-sm font-extrabold text-white truncate leading-tight">{ru.name}</h3>
                          <span className="inline-block text-xs font-bold text-yumder-teal mt-0.5">
                            {t.match.votesCount(ru.yes_count)}
                          </span>
                        </div>
                      </div>
                      <a
                        href={ruMapsUrl}
                        target="_blank"
                        rel="noreferrer noopener"
                        onClick={() => trackOutboundClick(sessionCode, ru.restaurant_id, 'maps')}
                        className="w-10 h-10 rounded-full bg-yumder-teal hover:bg-teal-400 text-neutral-900 flex items-center justify-center shrink-0 active:scale-90 transition-all shadow-md"
                        aria-label={t.match.runnerUpRouteAriaLabel(ru.name)}
                        title={t.match.mapsButton}
                      >
                        <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                          <path d="M12 21s-7-5.5-7-11a7 7 0 0 1 14 0c0 5.5-7 11-7 11z" strokeLinecap="round" strokeLinejoin="round" />
                          <circle cx="12" cy="10" r="2.5" />
                        </svg>
                      </a>
                    </div>
                    <div className="pt-1 border-t border-white/10 flex items-center justify-between gap-2 flex-wrap">
                      <div className="text-xs text-neutral-200 font-medium leading-tight">
                        {ruStreet && <p>{ruStreet}</p>}
                        {ruCityWithSuburb && <p className="text-neutral-400 font-normal">{ruCityWithSuburb}</p>}
                      </div>
                      {ruCuisine.length > 0 && (
                        <span className="px-3 py-0.5 rounded-full text-xs font-extrabold bg-yumder-pink text-white shrink-0">
                          {ruCuisine[0]}
                        </span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </section>
        )}
      </div>

      {/* Fixe 50/50 Bottom-Bar (immer sichtbar, Content scrollt darueber) */}
      <div className="relative z-30 shrink-0 p-4 pb-[calc(1.25rem+env(safe-area-inset-bottom,0px))] bg-neutral-950 border-t border-white/10 grid grid-cols-2 gap-2.5">
        <button
          onClick={onNewTable}
          className="py-3 px-3 bg-neutral-800 hover:bg-neutral-700 text-neutral-100 font-bold text-xs rounded-2xl border border-white/10 flex items-center justify-center gap-2 active:scale-[0.98] transition-all"
        >
          <svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-yumder-teal" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" />
            <path d="M21 3v5h-5" />
          </svg>
          {t.session.newTableButton}
        </button>
        <button
          onClick={onLeaveSession}
          className="py-3 px-3 bg-white hover:bg-neutral-200 text-black font-bold text-xs rounded-2xl flex items-center justify-center gap-2 active:scale-[0.98] transition-all"
        >
          <svg viewBox="0 0 24 24" className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
            <path d="M16 17l5-5-5-5M21 12H9" />
          </svg>
          {t.session.leaveSessionButton}
        </button>
      </div>
    </main>
  );
}
