'use client'

import { useState, useEffect, useRef } from 'react'
import maplibregl from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'
import {
  Flame, Loader2, MapPin, Save, MoreVertical, Clock,
  Moon, Maximize, ClipboardList, User, LogOut,
  MousePointer2, CircleDot, Minus, Pentagon, Square,
  Circle, Pencil, MoveRight, Type, Eraser, Ruler,
  Undo2, Redo2, Search, Map, Target,
  Droplets, AlertTriangle, Car, Users, Truck, Building, Upload,
} from 'lucide-react'

interface DemoProject {
  id: string
  title: string
  location?: string
  description?: string
  einsatzleiter?: string
  journalfuehrer?: string
  mapCenter: { lng: number; lat: number }
  mapZoom: number
}

interface DemoJournalEntry {
  id: string
  time: string
  what: string
  who: string | null
  done: boolean
  isCorrected?: boolean
}

interface DemoJournalCheckItem {
  id: string
  label: string
  confirmed: boolean
  ok: boolean
}

interface DemoJournalPendenz {
  id: string
  what: string
  who: string | null
  done: boolean
}

interface DemoFeature {
  id: string
  type: string
  geometry: { type: string; coordinates: any }
  properties: Record<string, any>
}

interface DemoCategory {
  id: string
  name: string
  symbols: { id: string; name: string; imageUrl: string }[]
}

/* ── Static data for demo toolbar ── */
const drawTools = [
  { icon: MousePointer2, label: 'Auswählen', active: true },
  { icon: CircleDot, label: 'Punkt' },
  { icon: Minus, label: 'Linie' },
  { icon: Pentagon, label: 'Polygon' },
  { icon: Square, label: 'Rechteck' },
  { icon: Circle, label: 'Kreis' },
  { icon: Pencil, label: 'Freihand' },
  { icon: MoveRight, label: 'Pfeil / Route' },
  { icon: Type, label: 'Text' },
  { icon: Eraser, label: 'Radiergummi' },
  { icon: Ruler, label: 'Messen' },
]

const colors = ['#ef4444','#f97316','#eab308','#22c55e','#3b82f6','#8b5cf6','#000000','#ffffff']

const categoryIcons: Record<string, typeof Flame> = {
  Feuer: Flame, Wasser: Droplets, Gefahren: AlertTriangle, Gefahrstoffe: AlertTriangle,
  Verkehr: Car, Personen: Users, Fahrzeuge: Truck, Infrastruktur: Building,
  Taktik: Target, Eigene: Upload,
}

export default function DemoPage() {
  const mapContainer = useRef<HTMLDivElement | null>(null)
  const map = useRef<maplibregl.Map | null>(null)
  const markersRef = useRef<maplibregl.Marker[]>([])
  const [project, setProject] = useState<DemoProject | null>(null)
  const [features, setFeatures] = useState<DemoFeature[]>([])
  const [journalEntries, setJournalEntries] = useState<DemoJournalEntry[]>([])
  const [journalCheckItems, setJournalCheckItems] = useState<DemoJournalCheckItem[]>([])
  const [journalPendenzen, setJournalPendenzen] = useState<DemoJournalPendenz[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')
  const [isMapLoaded, setIsMapLoaded] = useState(false)
  const [categories, setCategories] = useState<DemoCategory[]>([])
  const [activeCategory, setActiveCategory] = useState('')
  const [searchQuery, setSearchQuery] = useState('')
  const [activeTab, setActiveTab] = useState<'map' | 'journal'>('map')
  const [now, setNow] = useState(new Date())

  // Live clock
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000)
    return () => clearInterval(t)
  }, [])

  // Fetch demo data + icons
  useEffect(() => {
    async function load() {
      try {
        const [demoRes, iconsRes] = await Promise.all([
          fetch('/api/demo'),
          fetch('/api/icons'),
        ])
        if (demoRes.ok) {
          const d = await demoRes.json()
          setProject(d.project)
          setFeatures(d.features || [])
          if (d.journal) {
            setJournalEntries(d.journal.entries || [])
            setJournalCheckItems(d.journal.checkItems || [])
            setJournalPendenzen(d.journal.pendenzen || [])
          }
        } else {
          setError('Keine Demo verfügbar')
        }
        if (iconsRes.ok) {
          const d = await iconsRes.json()
          const cats: DemoCategory[] = (d.categories || [])
            .filter((c: any) => c.icons?.length > 0)
            .map((c: any) => ({
              id: c.id,
              name: c.name,
              symbols: c.icons.map((i: any) => ({
                id: i.id,
                name: i.name,
                imageUrl: i.url || `/api/icons/${i.id}/image`,
              })),
            }))
          setCategories(cats)
          if (cats.length > 0) setActiveCategory(cats[0].id)
        }
      } catch {
        setError('Demo konnte nicht geladen werden')
      } finally {
        setIsLoading(false)
      }
    }
    load()
  }, [])

  // Initialize map
  useEffect(() => {
    if (!mapContainer.current || !project || map.current) return

    const m = new maplibregl.Map({
      container: mapContainer.current,
      style: {
        version: 8,
        sources: {
          osm: {
            type: 'raster',
            tiles: [
              'https://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
              'https://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
              'https://c.tile.openstreetmap.org/{z}/{x}/{y}.png',
            ],
            tileSize: 256,
            maxzoom: 19,
            attribution: '&copy; OpenStreetMap contributors',
          },
        },
        layers: [{ id: 'osm', type: 'raster', source: 'osm' }],
      },
      center: [project.mapCenter.lng, project.mapCenter.lat],
      zoom: project.mapZoom,
      maxZoom: 19,
      attributionControl: false,
    })

    m.addControl(new maplibregl.NavigationControl(), 'bottom-right')
    m.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right')

    m.on('load', () => {
      setIsMapLoaded(true)
      // Force resize after load to ensure tiles render correctly
      setTimeout(() => m.resize(), 50)
    })
    map.current = m

    // Also resize after initial render in case container dimensions weren't ready
    requestAnimationFrame(() => m.resize())

    return () => { m.remove(); map.current = null }
  }, [project])

  // Render features on map
  useEffect(() => {
    if (!map.current || !isMapLoaded || features.length === 0) return
    const m = map.current

    markersRef.current.forEach(marker => marker.remove())
    markersRef.current = []

    if (!m.getSource('demo-features')) {
      m.addSource('demo-features', {
        type: 'geojson',
        data: { type: 'FeatureCollection', features: [] },
      })
      m.addLayer({
        id: 'demo-fill', type: 'fill', source: 'demo-features',
        filter: ['==', '$type', 'Polygon'],
        paint: { 'fill-color': ['coalesce', ['get', 'color'], '#ef4444'], 'fill-opacity': 0.2 },
      })
      m.addLayer({
        id: 'demo-line', type: 'line', source: 'demo-features',
        filter: ['==', '$type', 'LineString'],
        paint: { 'line-color': ['coalesce', ['get', 'color'], '#ef4444'], 'line-width': ['coalesce', ['get', 'width'], 3] },
      })
      m.addLayer({
        id: 'demo-outline', type: 'line', source: 'demo-features',
        filter: ['==', '$type', 'Polygon'],
        paint: { 'line-color': ['coalesce', ['get', 'color'], '#ef4444'], 'line-width': 2 },
      })
      m.addLayer({
        id: 'demo-point', type: 'circle', source: 'demo-features',
        filter: ['all', ['==', '$type', 'Point'], ['!=', ['get', 'featureType'], 'symbol'], ['!=', ['get', 'featureType'], 'text']],
        paint: { 'circle-radius': 6, 'circle-color': ['coalesce', ['get', 'color'], '#ef4444'], 'circle-stroke-width': 2, 'circle-stroke-color': '#fff' },
      })
    }

    const geoJsonFeatures: any[] = []
    features.forEach(f => {
      if (f.type === 'symbol' || f.type === 'text') return
      geoJsonFeatures.push({ type: 'Feature', geometry: f.geometry, properties: { ...f.properties, featureType: f.type } })
    })

    const src = m.getSource('demo-features') as maplibregl.GeoJSONSource
    if (src) src.setData({ type: 'FeatureCollection', features: geoJsonFeatures })

    features.forEach(f => {
      if (f.type === 'symbol' && f.geometry.type === 'Point') {
        const [lng, lat] = f.geometry.coordinates
        const el = document.createElement('div')
        const scale = (f.properties.scale as number) || 1
        const rotation = (f.properties.rotation as number) || 0
        const size = 40 * scale
        el.style.width = `${size}px`
        el.style.height = `${size}px`
        el.style.transform = `rotate(${rotation}deg)`
        el.style.pointerEvents = 'none'
        const img = document.createElement('img')
        img.src = f.properties.imageUrl as string || `/api/icons/${f.properties.iconId}/image`
        img.style.width = '100%'
        img.style.height = '100%'
        img.style.objectFit = 'contain'
        img.crossOrigin = 'anonymous'
        el.appendChild(img)
        const marker = new maplibregl.Marker({ element: el, anchor: 'center' }).setLngLat([lng, lat]).addTo(m)
        markersRef.current.push(marker)
      }
      if (f.type === 'text' && f.geometry.type === 'Point') {
        const [lng, lat] = f.geometry.coordinates
        const el = document.createElement('div')
        el.style.fontSize = `${f.properties.fontSize || 16}px`
        el.style.color = (f.properties.color as string) || '#000'
        el.style.fontWeight = '700'
        el.style.textShadow = '0 0 4px rgba(255,255,255,0.9), 0 0 8px rgba(255,255,255,0.7)'
        el.style.whiteSpace = 'nowrap'
        el.style.pointerEvents = 'none'
        el.textContent = f.properties.text as string || ''
        const marker = new maplibregl.Marker({ element: el, anchor: 'center' }).setLngLat([lng, lat]).addTo(m)
        markersRef.current.push(marker)
      }
    })
  }, [features, isMapLoaded])

  /* ── Derived data ── */
  const totalSymbols = categories.reduce((s, c) => s + c.symbols.length, 0)
  const currentCat = categories.find(c => c.id === activeCategory)
  const filteredSymbols = currentCat?.symbols.filter(s => s.name.toLowerCase().includes(searchQuery.toLowerCase())) || []

  /* ── Loading / Error states ── */
  if (isLoading) {
    return (
      <div className="w-full h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin text-red-500 mx-auto mb-2" />
          <p className="text-sm text-gray-500">Demo wird geladen...</p>
        </div>
      </div>
    )
  }

  if (error || !project) {
    return (
      <div className="w-full h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100">
        <div className="text-center">
          <div className="w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
            <Flame className="w-8 h-8 text-red-500" />
          </div>
          <h2 className="text-lg font-bold text-gray-900 mb-1">Lageplan Demo</h2>
          <p className="text-sm text-gray-500">Demo wird vorbereitet — bald verfügbar!</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-screen w-full flex flex-col bg-background text-foreground overflow-hidden">
      {/* ═══════ TOPBAR ═══════ */}
      <header className="h-12 border-b border-border bg-card flex items-center justify-between px-2 shrink-0">
        {/* Left */}
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-1.5">
            <div className="w-7 h-7 bg-primary rounded-md flex items-center justify-center">
              <MapPin className="w-4 h-4 text-primary-foreground" />
            </div>
            <span className="font-semibold text-sm hidden sm:inline">Lageplan</span>
          </div>
          <div className="h-5 w-px bg-border hidden sm:block" />
          <button className="h-8 px-2 text-xs border border-border rounded-md flex items-center gap-1 bg-background hover:bg-accent transition-colors">
            <Save className="w-3.5 h-3.5" />
            <span className="hidden md:inline">Speichern</span>
          </button>
          <button className="h-8 px-2 text-xs border border-border rounded-md flex items-center gap-1 bg-background hover:bg-accent transition-colors">
            <MoreVertical className="w-3.5 h-3.5" />
            <span className="hidden md:inline">Menü</span>
          </button>
        </div>

        {/* Right */}
        <div className="flex items-center gap-1.5">
          {/* Project info */}
          <div className="hidden lg:flex items-center gap-1.5 text-xs border border-border rounded-md px-2 py-1 bg-muted/30">
            <span className="font-semibold truncate max-w-[140px]">{project.title}</span>
            {project.location && (
              <><span className="text-muted-foreground">|</span><span className="text-muted-foreground truncate max-w-[120px]">{project.location}</span></>
            )}
          </div>
          {/* Clock */}
          <div className="hidden md:flex items-center gap-1 text-xs font-medium tabular-nums">
            <Clock className="w-3.5 h-3.5 text-muted-foreground" />
            <span className="text-primary font-bold">{now.toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' })}</span>
          </div>
          <button className="h-8 w-8 border border-border rounded-md hidden md:flex items-center justify-center hover:bg-accent transition-colors">
            <Moon className="w-3.5 h-3.5" />
          </button>
          <button className="h-8 w-8 border border-border rounded-md hidden md:flex items-center justify-center hover:bg-accent transition-colors">
            <Maximize className="w-3.5 h-3.5" />
          </button>
          <button className="h-8 w-8 border border-border rounded-md hidden md:flex items-center justify-center hover:bg-accent transition-colors relative">
            <ClipboardList className="w-3.5 h-3.5" />
            <span className="absolute -top-1 -right-1 w-3.5 h-3.5 bg-primary text-primary-foreground text-[8px] rounded-full flex items-center justify-center font-bold">
              {features.length > 0 ? features.length : 0}
            </span>
          </button>
          <div className="hidden md:flex items-center gap-1 ml-1 pl-1.5 border-l border-border">
            <User className="w-3.5 h-3.5 text-muted-foreground" />
            <span className="text-xs text-muted-foreground hidden lg:inline">adminroppe</span>
            <button className="h-7 w-7 flex items-center justify-center text-muted-foreground hover:text-destructive transition-colors">
              <LogOut className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>
      </header>

      {/* ═══════ MAIN AREA ═══════ */}
      <div className="flex flex-1 overflow-hidden">

        {/* ── LEFT TOOLBAR ── */}
        <aside className="w-11 md:w-14 border-r border-border bg-card flex flex-col items-center py-1.5 shrink-0 overflow-y-auto">
          <div className="flex flex-col gap-px">
            {drawTools.map((t, i) => (
              <button
                key={i}
                className={`w-8 h-8 md:w-10 md:h-10 rounded-md flex items-center justify-center transition-colors ${
                  t.active ? 'bg-primary text-primary-foreground' : 'text-foreground hover:bg-accent'
                }`}
                title={t.label}
              >
                <t.icon className="w-4 h-4 md:w-5 md:h-5" />
              </button>
            ))}
          </div>
          <div className="w-6 md:w-8 h-px bg-border my-1" />
          <div className="grid grid-cols-2 gap-px">
            <button className="w-5 h-5 md:w-6 md:h-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent transition-colors" title="Rückgängig">
              <Undo2 className="w-3.5 h-3.5" />
            </button>
            <button className="w-5 h-5 md:w-6 md:h-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent transition-colors" title="Wiederholen">
              <Redo2 className="w-3.5 h-3.5" />
            </button>
          </div>
          <div className="w-6 md:w-8 h-px bg-border my-1" />
          <div className="grid grid-cols-2 gap-0.5">
            {colors.map(c => (
              <div
                key={c}
                className={`w-4 h-4 md:w-5 md:h-5 rounded border-2 ${c === '#ef4444' ? 'border-primary ring-1 ring-primary ring-offset-1 scale-110' : 'border-muted'}`}
                style={{ backgroundColor: c }}
              />
            ))}
          </div>
        </aside>

        {/* ── MAP ── */}
        <main className="flex-1 relative overflow-hidden">
          <div ref={mapContainer} className="absolute inset-0" />

          {/* Satellite / Map toggle */}
          <div className="absolute top-2 right-2 z-10 flex rounded-md overflow-hidden border border-border shadow-sm text-xs">
            <button className="px-3 py-1.5 bg-muted/80 text-muted-foreground backdrop-blur-sm">Satellit</button>
            <button className="px-3 py-1.5 bg-card/90 text-foreground font-semibold backdrop-blur-sm border-l border-border">Karte</button>
          </div>

          {/* Scale bar */}
          <div className="absolute bottom-2 left-2 z-10 flex items-center gap-1.5 text-[10px] text-muted-foreground">
            <div className="border-b-2 border-l-2 border-r-2 border-foreground/40 w-16 h-2" />
            <span>1:500</span>
          </div>

          {/* CTA overlay */}
          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-10">
            <a
              href="/register"
              className="inline-flex items-center gap-2 bg-red-600 hover:bg-red-700 text-white px-5 py-2.5 rounded-full shadow-lg text-sm font-semibold transition-colors"
            >
              Kostenlos registrieren & loslegen →
            </a>
          </div>

          {/* DEMO badge */}
          <div className="absolute top-2 left-2 z-10 bg-red-100 text-red-700 px-2 py-0.5 rounded-full text-[10px] font-bold shadow-sm">
            DEMO
          </div>
        </main>

        {/* ── RIGHT SIDEBAR ── */}
        <aside className="hidden md:flex w-48 lg:w-56 xl:w-72 border-l border-border bg-card flex-col shrink-0">
          {/* Tab switcher */}
          <div className="flex border-b border-border shrink-0">
            <button
              onClick={() => setActiveTab('map')}
              className={`flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs font-medium transition-colors ${
                activeTab === 'map' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'text-muted-foreground hover:bg-accent'
              }`}
            >
              <Map className="w-3.5 h-3.5" /> Karte
            </button>
            <button
              onClick={() => setActiveTab('journal')}
              className={`flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs font-medium transition-colors ${
                activeTab === 'journal' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'text-muted-foreground hover:bg-accent'
              }`}
            >
              <ClipboardList className="w-3.5 h-3.5" /> Journal
            </button>
          </div>

          {activeTab === 'map' && (
            <>
              {/* Header + search */}
              <div className="p-2 lg:p-3 border-b border-border">
                <h3 className="font-semibold text-sm mb-1.5">Symbole</h3>
                <div className="relative">
                  <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="Suchen..."
                    value={searchQuery}
                    onChange={e => setSearchQuery(e.target.value)}
                    className="w-full pl-8 h-9 text-sm rounded-md border border-border bg-background px-3 focus:outline-none focus:ring-1 focus:ring-primary"
                  />
                </div>
                <p className="text-xs text-muted-foreground mt-1.5">{totalSymbols} Symbole verfügbar</p>
              </div>

              {/* Category pills */}
              <div className="p-1.5 border-b border-border">
                <div className="flex flex-wrap gap-0.5">
                  {categories.map(cat => {
                    const Icon = categoryIcons[cat.name] || Target
                    return (
                      <button
                        key={cat.id}
                        onClick={() => setActiveCategory(cat.id)}
                        className={`flex items-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-colors ${
                          activeCategory === cat.id
                            ? 'bg-primary text-primary-foreground'
                            : 'bg-muted hover:bg-accent text-muted-foreground'
                        }`}
                        title={`${cat.name} (${cat.symbols.length})`}
                      >
                        <Icon className="w-3.5 h-3.5" />
                        <span className="hidden lg:inline max-w-[70px] truncate">{cat.name}</span>
                      </button>
                    )
                  })}
                </div>
              </div>

              {/* Symbols grid */}
              <div className="flex-1 overflow-y-auto p-2">
                {currentCat && (
                  <>
                    <h4 className="text-xs font-medium text-muted-foreground mb-1.5">
                      {currentCat.name} ({filteredSymbols.length})
                    </h4>
                    <div className="grid grid-cols-2 lg:grid-cols-3 gap-1">
                      {filteredSymbols.map(sym => (
                        <div
                          key={sym.id}
                          className="flex flex-col items-center gap-1 p-1.5 lg:p-2 rounded-lg border-2 border-transparent hover:border-border hover:bg-accent cursor-grab transition-all"
                          title={sym.name}
                        >
                          <div className="w-10 h-10 lg:w-14 lg:h-14 flex items-center justify-center rounded-lg bg-muted">
                            <img
                              src={sym.imageUrl}
                              alt={sym.name}
                              className="w-8 h-8 lg:w-12 lg:h-12 object-contain"
                              crossOrigin="anonymous"
                            />
                          </div>
                          <span className="text-[10px] text-center truncate w-full font-medium text-muted-foreground">
                            {sym.name}
                          </span>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </>
          )}

          {activeTab === 'journal' && (
            <div className="flex-1 overflow-y-auto p-3">
              {/* Project info header */}
              {project && (
                <div className="border border-border rounded-lg p-3 bg-muted/30 mb-3">
                  <div className="text-xs font-semibold">{project.title}</div>
                  {project.location && <div className="text-[10px] text-muted-foreground">{project.location}</div>}
                  {project.einsatzleiter && <div className="text-[10px] text-muted-foreground">EL: {project.einsatzleiter}</div>}
                </div>
              )}

              {/* Check items */}
              {journalCheckItems.length > 0 && (
                <div className="mb-3">
                  <h4 className="text-xs font-semibold text-muted-foreground mb-1.5">Checkliste</h4>
                  <div className="space-y-1">
                    {journalCheckItems.map(item => (
                      <div key={item.id} className="flex items-center gap-2 text-xs px-2 py-1 rounded bg-muted/20">
                        <span className={`w-4 h-4 rounded border flex items-center justify-center text-[10px] ${item.confirmed ? 'bg-green-100 border-green-400 text-green-700' : 'border-gray-300'}`}>
                          {item.confirmed ? '✓' : ''}
                        </span>
                        <span className={item.confirmed ? 'line-through text-muted-foreground' : ''}>{item.label}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Journal entries */}
              <h4 className="text-xs font-semibold text-muted-foreground mb-1.5">Journal-Einträge</h4>
              {journalEntries.length === 0 ? (
                <div className="text-center text-muted-foreground py-6 text-xs">Keine Journal-Einträge vorhanden</div>
              ) : (
                <div className="space-y-1.5">
                  {journalEntries.map(entry => (
                    <div key={entry.id} className={`border border-border rounded-lg p-2.5 ${entry.isCorrected ? 'bg-red-50/50 dark:bg-red-950/20' : 'bg-muted/30'}`}>
                      <div className="flex items-center justify-between mb-0.5">
                        <span className={`text-xs font-semibold ${entry.isCorrected ? 'line-through text-muted-foreground' : ''}`}>
                          {entry.what}
                        </span>
                        <span className="text-[10px] text-muted-foreground tabular-nums">
                          {new Date(entry.time).toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                      {entry.who && <p className="text-[10px] text-muted-foreground">Wer: {entry.who}</p>}
                      {entry.done && <span className="text-[10px] text-green-600 font-medium">✓ Erledigt</span>}
                    </div>
                  ))}
                </div>
              )}

              {/* Pendenzen */}
              {journalPendenzen.length > 0 && (
                <div className="mt-3">
                  <h4 className="text-xs font-semibold text-muted-foreground mb-1.5">Pendenzen</h4>
                  <div className="space-y-1">
                    {journalPendenzen.map(p => (
                      <div key={p.id} className={`border border-border rounded p-2 text-xs ${p.done ? 'bg-green-50/50' : 'bg-orange-50/50'}`}>
                        <span className={p.done ? 'line-through text-muted-foreground' : 'font-medium'}>{p.what}</span>
                        {p.who && <span className="text-muted-foreground ml-1">({p.who})</span>}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </aside>
      </div>
    </div>
  )
}
