/* Hallmark · pre-emit critique: P5 H5 E5 S5 R5 V5 */
/* Hallmark · redesign: HomePage · studied-DNA: https://inihaus.de · macrostructure: Newsstand Feed */
import React, { useState } from 'react';
import { Search, Calendar, MapPin, Clock, ArrowRight, Plus, EyeOff, CheckCircle2, Edit3, ShieldAlert, Trash2 } from 'lucide-react';

export default function HomePage({
  events,
  user,
  onSelectEvent,
  onOpenCreateEvent,
  onToggleEventActive,
  onEditEvent,
  onDeleteEvent,
  branding
}) {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterMode, setFilterMode] = useState('all');

  const nowStr = new Date().toISOString().split('T')[0];

  const filteredEvents = events.filter((evt) => {
    const matchesSearch =
      evt.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (evt.description && evt.description.toLowerCase().includes(searchQuery.toLowerCase())) ||
      (evt.location && evt.location.toLowerCase().includes(searchQuery.toLowerCase()));

    if (!matchesSearch) return false;
    if (filterMode === 'upcoming') return evt.end_date >= nowStr;
    return true;
  });

  const primaryColor = branding?.primary_color || 'var(--brand-primary)';

  const showCommunityBox = branding?.show_community_info_box ?? true;
  const showSupportBox = branding?.show_support_box ?? true;
  const hasSidebar = showCommunityBox || showSupportBox;

  const isUserAdmin = user && (user.is_admin_user || user.is_staff || user.is_superuser);

  return (
    <div className="space-y-8 animate-in fade-in duration-200">
      {/* Hero Banner Masthead */}
      <div className="hallmark-panel rounded-sm p-6 sm:p-10 space-y-6 max-w-5xl mx-auto relative border border-grid">
        <div className="space-y-2 border-b border-grid pb-6">
          <div className="flex items-center gap-2">
            <span className="font-mono text-[10px] uppercase tracking-widest text-muted border border-grid px-2.5 py-1 rounded-sm inline-block">
              {branding?.app_name || "SCHICHT- & EVENTPORTAL"}
            </span>
            {branding?.custom_banner_text && (
              <span className="font-mono text-[10px] uppercase tracking-widest text-amber-500 bg-amber-500/10 border border-amber-500/20 px-2.5 py-1 rounded-sm inline-block font-bold">
                📢 {branding.custom_banner_text}
              </span>
            )}
          </div>

          <h2 className="font-serif text-3xl sm:text-5xl font-bold uppercase tracking-tight text-main leading-tight">
            Veranstaltungen & Schichtkoordination
          </h2>
          <p className="font-sans text-xs sm:text-sm text-muted max-w-2xl">
            Hier findest du aktuelle Termine, Arbeitsgruppen, Bar- & Tresendienste und Schichtpläne der Initiative.
          </p>
        </div>

        {/* Search & Filter Bar */}
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
          <div className="relative flex-1">
            <Search className="w-4 h-4 absolute left-3.5 top-3 text-muted" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Veranstaltung, Ort oder Suchbegriff..."
              className="w-full pl-10 pr-16 py-2 rounded-sm bg-subtle border border-grid text-main text-xs font-mono focus:outline-none focus:border-muted"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-3 top-2.5 text-[10px] font-mono text-muted hover:text-main"
              >
                [ CLEAR ]
              </button>
            )}
          </div>

          <div className="flex items-center gap-1.5 font-mono text-xs shrink-0">
            <button
              onClick={() => setFilterMode('all')}
              className={`px-3.5 py-1.5 rounded-sm transition border ${
                filterMode === 'all'
                  ? 'bg-surface-hover text-main border-grid font-bold shadow-sm'
                  : 'bg-subtle text-muted border-grid hover:text-main'
              }`}
            >
              ALLE PROGRAMME ({events.length})
            </button>
            <button
              onClick={() => setFilterMode('upcoming')}
              className={`px-3.5 py-1.5 rounded-sm transition border ${
                filterMode === 'upcoming'
                  ? 'bg-surface-hover text-main border-grid font-bold shadow-sm'
                  : 'bg-subtle text-muted border-grid hover:text-main'
              }`}
            >
              ANSTEHEND ({events.filter(e => e.end_date >= nowStr).length})
            </button>
          </div>
        </div>
      </div>

      {/* Main Content Stream & Sidebar Widget */}
      <div className="max-w-5xl mx-auto grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Events Grid Stream */}
        <div className={`${hasSidebar ? 'lg:col-span-3' : 'lg:col-span-4'} space-y-4`}>
          <div className="flex items-center justify-between border-b border-grid pb-3 font-mono">
            <h3 className="font-serif text-xl font-bold uppercase tracking-wide text-main flex items-center gap-2">
              <Calendar className="w-4.5 h-4.5 text-muted" /> Termine & Schichten
            </h3>
            {user && (
              <button
                onClick={onOpenCreateEvent}
                style={{ backgroundColor: primaryColor }}
                className="px-3.5 py-1.5 rounded-sm text-xs font-mono font-bold text-white transition flex items-center gap-1 hover:brightness-110 shadow-sm"
              >
                <Plus className="w-3.5 h-3.5" /> EVENT ANLEGEN
              </button>
            )}
          </div>

          {filteredEvents.length === 0 ? (
            <div className="hallmark-panel rounded-sm p-12 text-center text-xs font-mono text-muted border border-grid">
              {searchQuery
                ? `[ Keinen Eintrag für "${searchQuery}" gefunden ]`
                : '[ Keine Veranstaltungen vorhanden ]'}
            </div>
          ) : (
            <div className={`grid grid-cols-1 sm:grid-cols-2 ${hasSidebar ? '' : 'lg:grid-cols-3'} gap-4`}>
              {filteredEvents.map((evt) => {
                const taskAreaCount = evt.task_areas?.length || 0;
                const totalShifts = evt.task_areas?.reduce((acc, ta) => acc + (ta.shifts?.length || 0), 0) || 0;
                const isCoManager = user && evt.co_managers && evt.co_managers.some(cm => (typeof cm === 'object' ? cm.id === user.id : cm === user.id));
                const isCreator = user && (evt.created_by === user.id || evt.created_by?.id === user.id || isCoManager);
                const canManage = isUserAdmin || isCreator;

                return (
                  <div
                    key={evt.id}
                    className={`hallmark-card rounded-sm p-5 border transition flex flex-col justify-between space-y-4 group overflow-hidden ${
                      evt.is_active === false ? 'border-amber-500/40 opacity-80 bg-subtle' : 'border-grid'
                    }`}
                  >
                    <div className="space-y-3">
                      <div className="flex items-center justify-between text-[11px] font-mono text-muted gap-2">
                        <span className="flex items-center gap-1 bg-subtle px-2 py-0.5 rounded-sm border border-grid font-bold shrink-0">
                          <Clock className="w-3 h-3 text-muted" />
                          {new Date(evt.start_date).toLocaleDateString('de-DE')}
                        </span>
                        {evt.is_active === false ? (
                          <span className="text-amber-500 font-bold px-1.5 py-0.5 rounded-sm bg-amber-500/10 border border-amber-500/20 shrink-0">
                            [ DEAKTIVIERT ]
                          </span>
                        ) : evt.location ? (
                          <span className="flex items-center gap-1 text-muted truncate max-w-[130px]">
                            <MapPin className="w-3 h-3 shrink-0" />
                            <span className="truncate">{evt.location}</span>
                          </span>
                        ) : null}
                      </div>

                      <h4 className="font-serif text-lg font-bold uppercase text-main group-hover:text-amber-500 transition line-clamp-2">
                        {evt.title}
                      </h4>

                      {evt.description && (
                        <p className="text-xs text-muted font-sans line-clamp-2">{evt.description}</p>
                      )}

                      <div className="text-[10px] font-mono text-muted flex items-center gap-1.5 pt-1">
                        <span>{taskAreaCount} Bereiche</span>
                        <span>/</span>
                        <span>{totalShifts} Schichten</span>
                      </div>
                    </div>

                    <div className="pt-3 border-t border-grid space-y-2 font-mono">
                      <div className="flex flex-wrap items-center gap-1.5">
                        <button
                          onClick={() => onSelectEvent(evt.id)}
                          className="flex-1 min-w-[110px] py-1.5 px-3 rounded-sm text-xs font-mono font-bold bg-surface hover:bg-surface-hover text-main border border-grid transition flex items-center justify-center gap-1"
                        >
                          Schichtplan <ArrowRight className="w-3.5 h-3.5" />
                        </button>

                        {canManage && onEditEvent && (
                          <button
                            onClick={() => onEditEvent(evt)}
                            className="py-1.5 px-2.5 rounded-sm text-[10px] font-mono font-bold bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 hover:bg-indigo-500/20 transition flex items-center gap-1 shrink-0"
                            title="Veranstaltung & Schichten bearbeiten"
                          >
                            <Edit3 className="w-3.5 h-3.5" /> BEARBEITEN
                          </button>
                        )}

                        {canManage && onToggleEventActive && (
                          <button
                            onClick={() => onToggleEventActive(evt)}
                            className={`py-1.5 px-2 rounded-sm text-[10px] font-mono font-bold transition flex items-center gap-1 border shrink-0 ${
                              evt.is_active !== false
                                ? 'bg-amber-500/10 text-amber-500 border-amber-500/20 hover:bg-amber-500/20'
                                : 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20 hover:bg-emerald-500/20'
                            }`}
                            title={evt.is_active !== false ? 'Deaktivieren' : 'Aktivieren'}
                          >
                            {evt.is_active !== false ? <EyeOff className="w-3.5 h-3.5" /> : <CheckCircle2 className="w-3.5 h-3.5" />}
                          </button>
                        )}

                        {(isUserAdmin || (user && (evt.created_by === user.id || evt.created_by?.id === user.id))) && onDeleteEvent && (
                          <button
                            onClick={() => onDeleteEvent(evt)}
                            className="py-1.5 px-2 rounded-sm text-[10px] font-mono font-bold bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 transition flex items-center gap-1 shrink-0"
                            title="Veranstaltung unwiderruflich löschen"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Sidebar Info & Community Links Widget */}
        {hasSidebar && (
          <div className="space-y-4 font-mono text-xs">
            {showCommunityBox && (
              <div className="hallmark-panel rounded-sm p-4 border border-grid space-y-3">
                <h4 className="font-serif text-sm font-bold uppercase tracking-wide text-main border-b border-grid pb-2">
                  {branding?.community_info_title || "📌 Verein & Infos"}
                </h4>
                <div className="space-y-2 text-muted text-[11px] whitespace-pre-line">
                  {branding?.community_info_text || "Initiative e.V. Hausverein\nOffene Angebote, DIY-Kultur & engagierte Schichten."}
                </div>
              </div>
            )}

            {showSupportBox && (
              <div className="hallmark-panel rounded-sm p-4 border border-grid space-y-3">
                <h4 className="font-serif text-sm font-bold uppercase tracking-wide text-main border-b border-grid pb-2">
                  {branding?.support_box_title || "❤️ Unterstützen"}
                </h4>
                <p className="text-[11px] text-muted whitespace-pre-line">
                  {branding?.support_box_text || "Hilf mit als Helfer*in an der Bar, beim Essen kochen oder beim Auf- & Abbau."}
                </p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
