'use client';

import { useGameStore } from '@/stores/gameStore';
import { useLatestNotification, type LatestNotificationItem } from '@/hooks/useLatestNotification';
import { useNotificationLink } from '@/hooks/useNotificationLink';
import { deriveHudNotificationLook, formatTimeAgo } from './hudNotificationVariant';
import { Newspaper, ChevronRight } from 'lucide-react';
import { t } from '@/lib/i18n';

/**
 * Interactive footer Journal column.
 *
 * Layout (top → bottom):
 *   1. Shortcut card — the latest notable event. Single click routes to the
 *      event's context (notification mark-read + open JournalOverlay).
 *   2. "Journal" title with newspaper icon.
 *   3. Live events list — each row clickable, styled by type.
 *   Background: transparent newspaper SVG to reinforce the paper aesthetic.
 *
 * Uses existing endpoints: /api/player/:id/notifications and the existing
 * setJournalOpen() action from gameStore. No new backend surface.
 */
export function JournalFooterCol() {
  const { setJournalOpen } = useGameStore();
  const { latest, items, markAsRead } = useLatestNotification();
  // Phase 8.8 (2026-04-29) — résolution lien notif → ouverture lightbox
  const { trigger, hasLink } = useNotificationLink();

  const topEvents = items.slice(0, 6);

  const openEvent = (n: LatestNotificationItem) => {
    void markAsRead(n.id);
    // Si la notif a un lien actionnable (alliance:UUID, cartel:UUID, etc.),
    // on ouvre le lightbox correspondant. Sinon, on tombe sur le journal.
    if (hasLink(n.link)) {
      void trigger(n.link);
    } else {
      setJournalOpen(true);
    }
  };

  return (
    <div className="h-full flex flex-col journal-col-refresh">
      {/* Transparent newspaper SVG background */}
      <NewspaperBg />

      {/* Last event shortcut — above the title */}
      {latest ? (
        <button
          type="button"
          onClick={() => openEvent(latest)}
          className="journal-shortcut"
          aria-label={`Ouvrir l'événement : ${latest.title}`}
        >
          <div className="js-main">
            <div className="js-type">
              <EventTypeBadge notification={latest} />
            </div>
            <div className="js-title">{latest.title}</div>
          </div>
          <span className="js-time">{formatTimeAgo(latest.created_at)}</span>
          <ChevronRight size={12} className="js-arrow" />
        </button>
      ) : (
        <div className="journal-shortcut-empty" aria-hidden>
          <span className="js-type dim">AUCUN ÉVÉNEMENT RÉCENT</span>
        </div>
      )}

      {/* Journal title — v2 mockup f-head + f-title with inline SVG */}
      <div className="f-head">
        <button
          type="button"
          onClick={() => setJournalOpen(true)}
          className="f-title f-title-btn"
          aria-label="Ouvrir le journal"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
            <path d="M4 4h16v16H4zM8 8h8M8 12h8M8 16h5" />
          </svg>
          <span>{t('footer.journal')}</span>
        </button>
      </div>

      {/* Events list */}
      {topEvents.length > 0 ? (
        <div className="journal-events">
          {topEvents.map((n) => {
            const actionable = hasLink(n.link);
            return (
              <div
                key={n.id}
                className={`j-event ${n.is_read ? 'j-event-read' : ''}`}
                style={{ display: 'flex', alignItems: 'stretch', gap: 6 }}
              >
                <button
                  type="button"
                  onClick={() => openEvent(n)}
                  style={{ flex: 1, minWidth: 0, textAlign: 'left', background: 'transparent', border: 0, padding: 0 }}
                  aria-label={`Ouvrir : ${n.title}`}
                >
                  <div className="j-event-main">
                    <div className="j-event-type">
                      <EventTypeBadge notification={n} compact />
                    </div>
                    <div className="j-event-title">{n.title}</div>
                  </div>
                  <span className="j-event-time">{formatTimeAgo(n.created_at)}</span>
                </button>
                {actionable && (
                  <button
                    type="button"
                    onClick={() => openEvent(n)}
                    className="j-event-view-btn"
                    style={{
                      flexShrink: 0,
                      alignSelf: 'center',
                      padding: '3px 8px',
                      fontSize: 9,
                      fontWeight: 700,
                      letterSpacing: '.1em',
                      textTransform: 'uppercase',
                      background: 'rgba(212,168,67,0.15)',
                      border: '1px solid rgba(212,168,67,0.5)',
                      borderRadius: 4,
                      color: 'var(--color-gold-light)',
                      cursor: 'pointer',
                    }}
                  >
                    {t('notification.view_button')}
                  </button>
                )}
              </div>
            );
          })}
        </div>
      ) : (
        <div className="journal-empty-zone">
          <p>Les événements notables apparaîtront ici.</p>
        </div>
      )}
    </div>
  );
}

function EventTypeBadge({ notification, compact }: { notification: LatestNotificationItem; compact?: boolean }) {
  const look = deriveHudNotificationLook(notification);
  const label = notification.type.toUpperCase();
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 5,
        color: look.accent === 'red'
          ? 'var(--color-red-light)'
          : look.accent === 'gold'
            ? 'var(--color-gold-light)'
            : look.accent === 'green'
              ? '#8bffa8'
              : look.accent === 'purple'
                ? '#c880ff'
                : '#8cc8ff',
        fontFamily: 'var(--font-subtitle)',
        letterSpacing: compact ? '.14em' : '.18em',
        fontSize: compact ? 8 : 8.5,
        fontWeight: 700,
      }}
    >
      {!compact && (
        <span
          aria-hidden
          style={{
            width: 5,
            height: 5,
            borderRadius: '50%',
            background: 'currentColor',
            boxShadow: '0 0 6px currentColor',
            animation: notification.is_read ? undefined : 'pulseline 2s infinite',
          }}
        />
      )}
      {label}
    </span>
  );
}

/** Static newspaper SVG background — transparent, sits below content. */
function NewspaperBg() {
  return (
    <svg
      className="journal-bg"
      viewBox="0 0 200 260"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      aria-hidden
    >
      <rect x="8" y="8" width="184" height="244" rx="3" />
      <text x="100" y="28" fill="currentColor" stroke="none" fontFamily="UnifrakturCook,serif" fontSize="18" textAnchor="middle">
        Gazette
      </text>
      <line x1="16" y1="40" x2="184" y2="40" />
      <line x1="16" y1="44" x2="184" y2="44" />
      <text x="100" y="58" fill="currentColor" stroke="none" fontFamily="Bebas Neue,sans-serif" fontSize="8" letterSpacing="2" textAnchor="middle">
        ÉDITION DU SOIR
      </text>
      <line x1="16" y1="66" x2="184" y2="66" />
      <rect x="16" y="74" width="78" height="54" strokeDasharray="2 2" />
      <line x1="22" y1="88" x2="88" y2="88" />
      <line x1="22" y1="96" x2="82" y2="96" />
      <line x1="22" y1="104" x2="88" y2="104" />
      <line x1="22" y1="112" x2="70" y2="112" />
      <line x1="102" y1="74" x2="184" y2="74" />
      <line x1="102" y1="82" x2="184" y2="82" />
      <line x1="102" y1="90" x2="184" y2="90" />
      <line x1="102" y1="98" x2="170" y2="98" />
      <line x1="102" y1="108" x2="184" y2="108" />
      <line x1="102" y1="116" x2="184" y2="116" />
      <line x1="102" y1="124" x2="160" y2="124" />
      <line x1="16" y1="140" x2="184" y2="140" />
      <line x1="16" y1="150" x2="184" y2="150" />
      <line x1="16" y1="160" x2="170" y2="160" />
      <line x1="16" y1="170" x2="184" y2="170" />
      <line x1="16" y1="180" x2="150" y2="180" />
      <rect x="102" y="196" width="82" height="48" strokeDasharray="2 2" />
      <line x1="16" y1="200" x2="94" y2="200" />
      <line x1="16" y1="210" x2="94" y2="210" />
      <line x1="16" y1="220" x2="86" y2="220" />
      <line x1="16" y1="230" x2="94" y2="230" />
      <line x1="16" y1="240" x2="78" y2="240" />
    </svg>
  );
}
