'use client';

import { ReactNode, useState } from 'react';
import { ChevronDown } from 'lucide-react';

/**
 * HudStack renders two floating cards over the map.
 *
 *   Left  — Notification center. Shows the latest unread notification of ANY
 *           type (chaleur / arrestation / attaque / gang / mission unlock / ...).
 *           When collapsed, the title is the generic "Notification" — the
 *           specific alert content is hidden.
 *
 *   Right — Mission en cours. Shows the currently-active mission.
 *           When collapsed, the title is the generic "Mission en cours".
 *
 * Each card has a chevron collapse button. Click a collapsed card to re-expand.
 * Both cards are fully presentational — the parent decides WHEN to render them
 * and WHICH icon / accent / content to pass.
 */

export type HudAccent = 'red' | 'gold' | 'green' | 'blue' | 'purple';

const ACCENT_TOKENS: Record<HudAccent, { color: string; border: string }> = {
  red:    { color: 'var(--color-red-light)', border: 'var(--border-red)' },
  gold:   { color: 'var(--color-gold-light)', border: 'var(--border-gold)' },
  green:  { color: '#8bffa8',                 border: 'rgba(96,224,132,0.3)' },
  blue:   { color: '#8cc8ff',                 border: 'rgba(140,200,255,0.3)' },
  purple: { color: '#c880ff',                 border: 'rgba(200,128,255,0.3)' },
};

export interface HudNotification {
  accent: HudAccent;           // visual accent / border / pulse color
  icon: ReactNode;             // SVG icon shown in the title row
  specificTitle: string;       // shown when expanded
  message: ReactNode;          // body when expanded
  timeAgo?: string;            // e.g. "12m" — shown right of title row
  unreadCount?: number;        // if > 1, badge beside title
  primaryLabel?: string;
  onPrimary?: () => void;
  secondaryLabel?: string;
  onSecondary?: () => void;
}

export interface HudMission {
  icon: ReactNode;             // SVG icon shown in the title row
  title: string;               // mission headline
  subline?: ReactNode;         // step / timer / meta
  accent?: HudAccent;          // defaults to 'gold'
  primaryLabel?: string;
  onPrimary?: () => void;
}

interface HudStackProps {
  notification?: HudNotification | null;
  mission?: HudMission | null;
  className?: string;
}

export function HudStack({ notification, mission, className }: HudStackProps) {
  if (!notification && !mission) return null;

  return (
    <div
      className={`absolute top-4 left-4 right-4 z-[6] grid gap-3 pointer-events-none ${className ?? ''}`}
      style={{ gridTemplateColumns: '1fr 1fr' }}
    >
      <div className="justify-self-start w-full max-w-[440px] pointer-events-auto">
        {notification ? (
          <NotificationCard notification={notification} />
        ) : (
          <div aria-hidden className="invisible h-0" />
        )}
      </div>
      <div className="justify-self-end w-full max-w-[440px] pointer-events-auto">
        {mission ? (
          <MissionCard mission={mission} />
        ) : (
          <div aria-hidden className="invisible h-0" />
        )}
      </div>
    </div>
  );
}

function NotificationCard({ notification }: { notification: HudNotification }) {
  const [collapsed, setCollapsed] = useState(false);

  return (
    <HudCardShell
      accent={notification.accent}
      pulse={notification.accent === 'red'}
      collapsed={collapsed}
      onToggle={() => setCollapsed((c) => !c)}
      icon={notification.icon}
      expandedTitle={notification.specificTitle}
      collapsedTitle="Notification"
      meta={
        <>
          {notification.unreadCount && notification.unreadCount > 1 && (
            <span
              style={{
                display: 'inline-grid',
                placeItems: 'center',
                minWidth: 18,
                height: 18,
                padding: '0 5px',
                borderRadius: 9,
                background: 'linear-gradient(180deg, var(--color-red-light), var(--color-red-dark))',
                color: '#fff',
                fontSize: 10,
                fontWeight: 700,
                boxShadow: '0 0 6px rgba(196,30,30,0.5)',
              }}
              aria-label={`${notification.unreadCount} notifications non lues`}
            >
              {notification.unreadCount > 9 ? '9+' : notification.unreadCount}
            </span>
          )}
          {notification.timeAgo && (
            <span style={{ fontFamily: 'monospace', color: 'var(--text-muted)', fontSize: 10 }}>
              {notification.timeAgo}
            </span>
          )}
        </>
      }
    >
      <div style={{ fontSize: 13, lineHeight: 1.45, color: 'var(--text-primary)' }}>{notification.message}</div>
      {(notification.primaryLabel || notification.secondaryLabel) && (
        <div className="mt-2 flex gap-2 flex-wrap">
          {notification.primaryLabel && (
            <button
              type="button"
              onClick={notification.onPrimary}
              className="btn-primary px-3 py-1.5 text-xs"
            >
              {notification.primaryLabel}
            </button>
          )}
          {notification.secondaryLabel && (
            <button
              type="button"
              onClick={notification.onSecondary}
              className="btn-ghost px-3 py-1.5 text-xs"
            >
              {notification.secondaryLabel}
            </button>
          )}
        </div>
      )}
    </HudCardShell>
  );
}

function MissionCard({ mission }: { mission: HudMission }) {
  const [collapsed, setCollapsed] = useState(false);
  const accent = mission.accent ?? 'gold';

  return (
    <HudCardShell
      accent={accent}
      pulse={false}
      collapsed={collapsed}
      onToggle={() => setCollapsed((c) => !c)}
      icon={mission.icon}
      expandedTitle="Mission active"
      collapsedTitle="Mission en cours"
    >
      <div style={{ fontSize: 13, lineHeight: 1.45, color: 'var(--text-primary)' }}>
        <b style={{ color: 'var(--color-gold-light)' }}>{mission.title}</b>
        {mission.subline && (
          <div style={{ marginTop: 4, color: 'var(--text-secondary)' }}>{mission.subline}</div>
        )}
      </div>
      {mission.primaryLabel && (
        <div className="mt-2">
          <button
            type="button"
            onClick={mission.onPrimary}
            className="btn-gold px-3 py-1.5 text-xs"
          >
            {mission.primaryLabel}
          </button>
        </div>
      )}
    </HudCardShell>
  );
}

interface HudCardShellProps {
  accent: HudAccent;
  pulse: boolean;
  icon: ReactNode;
  expandedTitle: string;
  collapsedTitle: string;
  collapsed: boolean;
  onToggle: () => void;
  meta?: ReactNode;
  children: ReactNode;
}

function HudCardShell({
  accent, pulse, icon, expandedTitle, collapsedTitle, collapsed, onToggle, meta, children,
}: HudCardShellProps) {
  const tokens = ACCENT_TOKENS[accent];

  return (
    <div
      className="relative overflow-hidden"
      style={{
        background: 'linear-gradient(180deg, rgba(20,20,28,0.92), rgba(14,14,22,0.96))',
        backdropFilter: 'blur(16px)',
        border: `1px solid ${tokens.border}`,
        borderRadius: 14,
        padding: collapsed ? '10px 44px 10px 16px' : '14px 44px 14px 16px',
        boxShadow: '0 10px 32px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.04)',
        cursor: collapsed ? 'pointer' : 'default',
        transition: 'padding .2s cubic-bezier(.4,0,.2,1)',
      }}
      onClick={(e) => {
        if (collapsed && !(e.target as HTMLElement).closest('.hud-collapse-btn')) {
          onToggle();
        }
      }}
    >
      {/* Top accent line */}
      <div
        aria-hidden
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          height: 1,
          background: `linear-gradient(90deg, transparent, ${tokens.color}, transparent)`,
          animation: pulse ? 'pulseline 2s infinite' : undefined,
        }}
      />

      {/* Collapse button */}
      <button
        type="button"
        onClick={(e) => {
          e.stopPropagation();
          onToggle();
        }}
        className="hud-collapse-btn"
        aria-label={collapsed ? 'Déplier la carte' : 'Réduire la carte'}
        title={collapsed ? 'Déplier' : 'Réduire'}
        style={{
          position: 'absolute',
          top: 10,
          right: 10,
          width: 24,
          height: 24,
          display: 'grid',
          placeItems: 'center',
          borderRadius: 6,
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid var(--border-dark)',
          color: 'var(--text-muted)',
          cursor: 'pointer',
          transition: 'all .15s',
          zIndex: 3,
        }}
      >
        <ChevronDown
          size={12}
          style={{ transform: collapsed ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform .2s' }}
        />
      </button>

      {/* Title row */}
      <div
        style={{
          fontFamily: 'var(--font-subtitle)',
          letterSpacing: '.2em',
          fontSize: 10,
          color: 'var(--text-muted)',
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          marginBottom: collapsed ? 0 : 8,
        }}
      >
        <span style={{ color: tokens.color, display: 'inline-flex' }}>{icon}</span>
        <span>{collapsed ? collapsedTitle : expandedTitle}</span>
        {meta && <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{meta}</span>}
      </div>

      {/* Body — hidden when collapsed */}
      {!collapsed && <>{children}</>}
    </div>
  );
}
