'use client';

import { useEffect, useState } from 'react';
import { X, ChevronLeft, ChevronRight, Newspaper, Briefcase, ShoppingBag, Radio, User, Crown } from 'lucide-react';
import { useGameStore } from '@/stores/gameStore';
import { apiFetch } from '@/lib/api';
import { useLatestNotification } from '@/hooks/useLatestNotification';
import { useNotificationLink } from '@/hooks/useNotificationLink';
import { t, tFmt } from '@/lib/i18n';

type JournalSection = 'evenements' | 'infos' | 'emploi' | 'marche';

export function JournalOverlay() {
  const { isJournalOpen, setJournalOpen } = useGameStore();
  const [section, setSection] = useState<JournalSection>('evenements');

  useEffect(() => {
    if (!isJournalOpen) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setJournalOpen(false);
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [isJournalOpen, setJournalOpen]);

  if (!isJournalOpen) return null;

  return (
    <div className="fixed inset-0 z-[1800] pointer-events-none">
      <div className="absolute inset-0 pointer-events-auto" onClick={() => setJournalOpen(false)} style={{ background: 'rgba(0,0,0,0.35)' }} />
      <div
        className="absolute left-3 top-[70px] bottom-[220px] w-[440px] pointer-events-auto rounded-2xl overflow-hidden flex flex-col"
        style={{ background: '#f5f1e8', border: '1px solid rgba(0,0,0,0.15)', boxShadow: '0 20px 80px rgba(0,0,0,0.35)' }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-4 py-3" style={{ borderBottom: '1px solid rgba(0,0,0,0.12)' }}>
          <div className="flex items-center gap-2">
            <Newspaper size={18} style={{ color: '#1f2937' }} />
            <div className="leading-tight">
              <p className="text-[11px] font-bold tracking-wide" style={{ color: '#111827' }}>{t('footer.journal')}</p>
              <p className="text-[9px]" style={{ color: '#6b7280' }}>Ombres & Lumières</p>
            </div>
          </div>
          <button onClick={() => setJournalOpen(false)} className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80" style={{ background: 'rgba(0,0,0,0.04)' }}>
            <X size={16} style={{ color: '#111827' }} />
          </button>
        </div>

        <div className="px-3 py-2 flex items-center gap-2">
          <SectionButton id="evenements" icon={Radio} label="Événements" active={section === 'evenements'} onClick={() => setSection('evenements')} />
          <SectionButton id="infos" icon={Newspaper} label={t('footer.journal_infos')} active={section === 'infos'} onClick={() => setSection('infos')} />
          <SectionButton id="emploi" icon={Briefcase} label={t('footer.journal_emploi')} active={section === 'emploi'} onClick={() => setSection('emploi')} />
          <SectionButton id="marche" icon={ShoppingBag} label={t('footer.journal_marche')} active={section === 'marche'} onClick={() => setSection('marche')} />
        </div>

        <div className="flex-1 overflow-y-auto px-4 pb-4">
          {section === 'evenements' ? <EventsContent /> : <JournalContent section={section} />}
        </div>
      </div>
    </div>
  );
}

function SectionButton(props: { id: string; icon: any; label: string; active: boolean; onClick: () => void }) {
  const Icon = props.icon;
  return (
    <button
      type="button"
      onClick={props.onClick}
      className="flex-1 flex items-center gap-2 px-3 py-2 rounded-xl transition-colors"
      style={{
        background: props.active ? 'rgba(17,24,39,0.08)' : 'rgba(17,24,39,0.03)',
        border: props.active ? '1px solid rgba(17,24,39,0.18)' : '1px solid rgba(17,24,39,0.08)',
      }}
    >
      <Icon size={14} style={{ color: '#111827' }} />
      <span className="text-[10px] font-semibold truncate" style={{ color: '#111827' }}>{props.label}</span>
    </button>
  );
}

/** Section "Événements" — centralise les notifications map / crimes / attaques /
 *  incarcérations / prises de cartel dans le journal principal (unification
 *  Phase 14, 19-04-2026 : même contenu que JournalFooterCol mais élargi). */
/**
 * Phase 8.5d (2026-04-29) — Refonte 2 colonnes Perso/Cartel.
 * Spec user :
 *   - 2 colonnes côte à côte pleine hauteur
 *   - Pagination 9 entrées par colonne
 *   - Scroll invisible (pas de barre)
 *   - Cartel filtré sur types `cartel*`, `alliance_*`, `racket_*`
 *   - Perso = tout le reste
 */
const CARTEL_TYPES = new Set([
  'cartel', 'cartel_territory_lost', 'cartel_takeover', 'cartel_invitation',
  'cartel_dissolved', 'cartel_power_struggle',
  'alliance_proposal', 'alliance_accepted', 'alliance_rejected', 'alliance_message',
  'racket_zone_attacked', 'racket_zone_revenue_collected',
]);
const PAGE_SIZE = 9;

function EventsContent() {
  const { items, markAsRead } = useLatestNotification();
  const { trigger, hasLink } = useNotificationLink();
  const [pagePerso, setPagePerso] = useState(0);
  const [pageCartel, setPageCartel] = useState(0);

  const cartelItems = (items || []).filter((n: any) => CARTEL_TYPES.has(n.type));
  const persoItems = (items || []).filter((n: any) => !CARTEL_TYPES.has(n.type));

  const onView = async (n: any) => {
    void markAsRead(n.id);
    void trigger(n.link);
  };

  return (
    <div className="grid grid-cols-2 gap-3 h-full">
      <NotifColumn
        label={t('journal.section_perso')}
        Icon={User}
        items={persoItems}
        page={pagePerso}
        setPage={setPagePerso}
        emptyMsg={t('journal.no_perso')}
        onView={onView}
        hasLink={hasLink}
        markAsRead={markAsRead}
      />
      <NotifColumn
        label={t('journal.section_cartel')}
        Icon={Crown}
        items={cartelItems}
        page={pageCartel}
        setPage={setPageCartel}
        emptyMsg={t('journal.no_cartel')}
        onView={onView}
        hasLink={hasLink}
        markAsRead={markAsRead}
      />
    </div>
  );
}

function NotifColumn({ label, Icon, items, page, setPage, emptyMsg, onView, hasLink, markAsRead }: {
  label: string;
  Icon: typeof User;
  items: any[];
  page: number;
  setPage: (p: number) => void;
  emptyMsg: string;
  onView: (n: any) => void;
  hasLink: (link: string | null | undefined) => boolean;
  markAsRead: (id: string) => Promise<void> | void;
}) {
  const totalPages = Math.max(1, Math.ceil(items.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages - 1);
  const slice = items.slice(safePage * PAGE_SIZE, (safePage + 1) * PAGE_SIZE);

  const formatHour = (iso: string): string => {
    try {
      return new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
    } catch { return ''; }
  };

  return (
    <div className="flex flex-col h-full min-h-0">
      <div className="flex items-center gap-1.5 mb-2">
        <Icon size={12} style={{ color: '#374151' }} />
        <h4 className="text-[10px] font-bold uppercase tracking-[.1em]" style={{ color: '#111827' }}>{label}</h4>
        {items.length > 0 && (
          <span className="ml-auto text-[9px]" style={{ color: '#6b7280' }}>
            {tFmt('journal.page_label', { current: safePage + 1, total: totalPages })}
          </span>
        )}
      </div>

      {items.length === 0 ? (
        <p className="text-[10px] italic" style={{ color: '#6b7280' }}>{emptyMsg}</p>
      ) : (
        <>
          <div className="flex-1 overflow-y-auto journal-no-scrollbar space-y-1.5 min-h-0">
            {slice.map((n: any) => {
              const actionable = hasLink(n.link);
              return (
                <div key={n.id} className="flex items-stretch gap-2 p-2 rounded-lg"
                  style={{
                    background: n.is_read ? 'rgba(17,24,39,0.02)' : 'rgba(17,24,39,0.06)',
                    border: '1px solid rgba(17,24,39,0.10)',
                  }}>
                  <button type="button" onClick={() => actionable ? onView(n) : markAsRead(n.id)}
                    className="flex-1 text-left min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <span className="text-[8px] uppercase tracking-widest truncate" style={{ color: '#6b7280' }}>
                        {n.type || 'event'}
                      </span>
                      <span className="text-[8px]" style={{ color: '#9ca3af' }}>{formatHour(n.created_at)}</span>
                    </div>
                    <p className="text-[10px] font-bold truncate" style={{ color: '#111827' }}>{n.title}</p>
                    {n.message && <p className="text-[9px]" style={{ color: '#374151', lineHeight: 1.4 }}>{n.message}</p>}
                  </button>
                  {actionable && (
                    <button type="button" onClick={() => onView(n)}
                      className="self-center px-2 py-1 rounded text-[9px] font-bold uppercase tracking-[.1em]"
                      style={{ background: '#111827', color: '#f5f1e8', whiteSpace: 'nowrap', flexShrink: 0 }}>
                      {t('notification.view_button')}
                    </button>
                  )}
                </div>
              );
            })}
          </div>

          {totalPages > 1 && (
            <div className="flex items-center justify-between mt-2 pt-2" style={{ borderTop: '1px solid rgba(17,24,39,0.08)' }}>
              <button type="button" disabled={safePage === 0}
                onClick={() => setPage(Math.max(0, safePage - 1))}
                className="text-[9px] px-2 py-1 rounded disabled:opacity-30"
                style={{ background: 'rgba(17,24,39,0.04)', color: '#111827' }}>
                ← {t('common.previous') || 'Préc.'}
              </button>
              <button type="button" disabled={safePage >= totalPages - 1}
                onClick={() => setPage(Math.min(totalPages - 1, safePage + 1))}
                className="text-[9px] px-2 py-1 rounded disabled:opacity-30"
                style={{ background: 'rgba(17,24,39,0.04)', color: '#111827' }}>
                {t('common.next') || 'Suiv.'} →
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function JournalContent({ section }: { section: Exclude<JournalSection, 'evenements'> }) {
  const [items, setItems] = useState<{ id: string; title: string; description?: string; content?: string; salary?: number; type?: string; hourly_rate?: number; min_hours?: number; max_hours?: number }[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<typeof items[0] | null>(null);
  const [applying, setApplying] = useState<string | null>(null);
  const [applyMsg, setApplyMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);

  useEffect(() => {
    setLoading(true);
    setSelected(null);
    setApplyMsg(null);
    const endpoint =
      section === 'infos' ? '/api/blog/posts' :
      section === 'emploi' ? '/api/employment/catalog' :
      '/api/marketplace/listings';

    apiFetch<any>(endpoint)
      .then((res) => {
        const data = Array.isArray(res) ? res : res?.posts ?? res?.data ?? res?.items ?? [];
        setItems((data as any[]).slice(0, 30).map((item: any) => ({
          id: item.id || item._id || item.type || String(Math.random()),
          title: item.title || item.name || item.job_title || t('common.no_title'),
          description: item.description || item.excerpt || item.schedule || '',
          content: item.content || item.body || '',
          salary: item.revenue_per_payslip || item.price || undefined,
          type: item.type || undefined,
          hourly_rate: item.hourly_rate || undefined,
          min_hours: item.min_hours || undefined,
          max_hours: item.max_hours || undefined,
        })));
      })
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, [section]);

  const handleApply = async (jobType: string) => {
    setApplying(jobType);
    setApplyMsg(null);
    try {
      await apiFetch('/api/employment/apply', {
        method: 'POST',
        body: JSON.stringify({ type: jobType }),
        headers: { 'Content-Type': 'application/json' },
      });
      setApplyMsg({ type: 'ok', text: 'Embauche reussie !' });
    } catch (err: any) {
      setApplyMsg({ type: 'err', text: err.message || 'Candidature refusee' });
    } finally {
      setApplying(null);
    }
  };

  if (loading) return <p className="text-[10px]" style={{ color: '#6b7280' }}>{t('common.loading')}</p>;
  if (items.length === 0) return <p className="text-[10px]" style={{ color: '#6b7280' }}>{t('footer.no_content')}</p>;

  if (selected) {
    const isJob = section === 'emploi' && selected.type;
    return (
      <div>
        <button onClick={() => { setSelected(null); setApplyMsg(null); }} className="flex items-center gap-1 mb-3 text-[10px] hover:opacity-80" style={{ color: '#111827' }}>
          <ChevronLeft size={12} /> {t('common.back')}
        </button>
        <h4 className="text-[13px] font-bold mb-2" style={{ color: '#111827' }}>{selected.title}</h4>
        {selected.hourly_rate != null && (
          <p className="text-[11px] font-bold mb-1" style={{ color: '#7c2d12' }}>{selected.hourly_rate}∞/h</p>
        )}
        {selected.min_hours != null && selected.max_hours != null && (
          <p className="text-[10px] mb-1" style={{ color: '#6b7280' }}>Shift : {selected.min_hours}h - {selected.max_hours}h</p>
        )}
        {selected.description && (
          <p className="text-[11px] leading-relaxed" style={{ color: '#374151' }}>{selected.description}</p>
        )}
        {selected.content && (
          <p className="text-[10px] leading-relaxed mt-2" style={{ color: '#6b7280' }}>
            {selected.content.length > 900 ? selected.content.slice(0, 900) + '...' : selected.content}
          </p>
        )}
        {applyMsg && (
          <p className="text-[10px] mt-2 px-2 py-1 rounded" style={{
            color: applyMsg.type === 'ok' ? '#15803d' : '#dc2626',
            background: applyMsg.type === 'ok' ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)',
          }}>{applyMsg.text}</p>
        )}
        {isJob && (
          <button
            onClick={() => handleApply(selected.type!)}
            disabled={applying === selected.type}
            className="mt-3 w-full py-2 rounded-lg text-[11px] font-bold"
            style={{
              background: applying === selected.type ? 'rgba(17,24,39,0.06)' : '#111827',
              color: applying === selected.type ? '#6b7280' : '#f5f1e8',
            }}
          >
            {applying === selected.type ? 'Candidature...' : 'Postuler'}
          </button>
        )}
      </div>
    );
  }

  const featured = items[0];
  const rest = items.slice(1);

  return (
    <div className="space-y-3">
      {featured && (
        <div className="p-3 rounded-xl cursor-pointer hover:opacity-90" style={{ background: 'rgba(17,24,39,0.04)', border: '1px solid rgba(17,24,39,0.10)' }} onClick={() => setSelected(featured)}>
          <p className="text-[9px] uppercase tracking-widest mb-1" style={{ color: '#6b7280' }}>{section === 'emploi' ? 'Offre vedette' : t('footer.journal')}</p>
          <p className="text-[12px] font-bold" style={{ color: '#111827' }}>{featured.title}</p>
          {featured.hourly_rate != null ? (
            <p className="text-[10px] mt-1 font-bold" style={{ color: '#7c2d12' }}>{featured.hourly_rate}∞/h</p>
          ) : featured.description ? (
            <p className="text-[10px] mt-1" style={{ color: '#374151' }}>{featured.description}</p>
          ) : null}
        </div>
      )}

      <div className="grid grid-cols-2 gap-2">
        {rest.map((item) => (
          <div key={item.id} className="p-2 rounded-lg cursor-pointer hover:opacity-90 flex items-start gap-2" style={{ background: 'rgba(17,24,39,0.02)', border: '1px solid rgba(17,24,39,0.08)' }} onClick={() => setSelected(item)}>
            <ChevronRight size={12} style={{ color: '#6b7280' }} />
            <div className="min-w-0">
              <p className="text-[10px] font-semibold truncate" style={{ color: '#111827' }}>{item.title}</p>
              {item.hourly_rate != null ? (
                <p className="text-[9px]" style={{ color: '#7c2d12' }}>{item.hourly_rate}∞/h</p>
              ) : item.description ? (
                <p className="text-[9px] truncate" style={{ color: '#6b7280' }}>{item.description}</p>
              ) : null}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

