import React from 'react';
import { X, ShieldAlert, FileText, Lock, Activity } from 'lucide-react';
import { useApp } from '../context/AppContext';

export const ContentModal: React.FC = () => {
  const { state, pages, menuItems, totalGeneratedMoney, payments, listings, closeContentModal, t, tNum, settings } = useApp();

  if (!state.activeContentModal) return null;

  const page = pages.find(p => p.id === state.activeContentModal || p.slug === state.activeContentModal);
  const menuItem = !page
    ? menuItems.find(
        m =>
          m.id === state.activeContentModal ||
          m.url === `#${state.activeContentModal}` ||
          m.title.toLowerCase() === state.activeContentModal?.toLowerCase()
      )
    : null;

  if (!page && !menuItem) return null;

  const title = page ? page.title : menuItem?.title || 'Details';
  const content = page ? page.content : menuItem?.description || 'No description provided.';

  const getModalIcon = () => {
    switch (state.activeContentModal) {
      case 'rules': return <ShieldAlert className="w-5 h-5 text-amber-400" />;
      case 'terms': return <FileText className="w-5 h-5 text-emerald-400" />;
      case 'privacy': return <Lock className="w-5 h-5 text-sky-400" />;
      case 'stats': return <Activity className="w-5 h-5 text-purple-400" />;
      default: return <FileText className="w-5 h-5 text-emerald-400" />;
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 md:p-6 bg-black/80 backdrop-blur-sm animate-in fade-in duration-150"
      onClick={closeContentModal}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-2xl rounded-2xl border p-4 sm:p-6 shadow-2xl space-y-4 text-left relative transform transition-all max-h-[92dvh] sm:max-h-[88dvh] flex flex-col overflow-hidden"
        style={{
          backgroundColor: 'var(--card-color, #13181D)',
          borderColor: 'var(--border-color, #2A3440)'
        }}
      >
        <div
          className="flex items-center justify-between border-b pb-3 shrink-0"
          style={{ borderColor: 'var(--border-color, #222A33)' }}
        >
          <div className="flex items-center gap-2.5">
            {getModalIcon()}
            <h2
              className="font-bold text-base sm:text-lg font-mono truncate"
              style={{ color: 'var(--heading-color, #FFFFFF)' }}
            >
              {title}
            </h2>
          </div>
          <button
            onClick={closeContentModal}
            className="p-1.5 rounded-lg text-slate-400 hover:text-slate-200 dark:hover:text-white cursor-pointer transition-colors"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Live Stats Custom View */}
        {state.activeContentModal === 'stats' && (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 py-2">
            <div
              className="p-3 rounded-xl border text-center"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <span
                className="text-[10px] uppercase font-bold block"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {t('stat_total_listings', undefined, 'Total Listings')}
              </span>
              <span
                className="text-lg font-bold font-mono"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {tNum(listings.length)}
              </span>
            </div>
            <div
              className="p-3 rounded-xl border text-center"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <span
                className="text-[10px] uppercase font-bold block"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {t('stat_verified_txns', undefined, 'Verified Txns')}
              </span>
              <span className="text-lg font-bold font-mono text-emerald-500">{tNum(payments.filter(p => p.status === 'success').length)}</span>
            </div>
            <div
              className="p-3 rounded-xl border text-center"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <span
                className="text-[10px] uppercase font-bold block"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {t('stat_live_visitors', undefined, 'Live Visitors')}
              </span>
              <span className="text-lg font-bold font-mono text-amber-500">{tNum(state.activeVisitors)}</span>
            </div>
            <div
              className="p-3 rounded-xl border text-center"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <span
                className="text-[10px] uppercase font-bold block"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {t('stat_total_volume', undefined, 'Total Volume')}
              </span>
              <span className="text-lg font-bold font-mono text-teal-500">{settings.currency_symbol}{tNum(totalGeneratedMoney)}</span>
            </div>
          </div>
        )}

        {/* Markdown-style content display */}
        <div
          className="max-w-none text-xs sm:text-sm space-y-3 leading-relaxed max-h-[60vh] overflow-y-auto pr-2 flex-1 overscroll-contain"
          style={{ color: 'var(--text-color, #A0AEC0)' }}
        >
          {content.split('\n\n').map((para, i) => {
            if (para.startsWith('# ')) {
              return (
                <h3
                  key={i}
                  className="text-base font-bold mt-2"
                  style={{ color: 'var(--heading-color, #FFFFFF)' }}
                >
                  {para.replace('# ', '')}
                </h3>
              );
            }
            if (para.startsWith('### ')) {
              return <h4 key={i} className="text-sm font-semibold text-emerald-500 mt-2">{para.replace('### ', '')}</h4>;
            }
            return <p key={i}>{para}</p>;
          })}
        </div>

        <div
          className="pt-3 border-t flex justify-end shrink-0"
          style={{ borderColor: 'var(--border-color, #222A33)' }}
        >
          <button
            onClick={closeContentModal}
            className="px-5 py-2 rounded-xl bg-slate-700 hover:bg-slate-600 text-white text-xs font-semibold cursor-pointer"
          >
            {t('close_btn', undefined, 'Close')}
          </button>
        </div>
      </div>
    </div>
  );
};
