// app.jsx – Predigerplanungs-App v5
const { useState, useEffect, useRef } = React;

function formatDatum(ds) {
  if (!ds) return "Noch nicht eingeplant";
  const d = new Date(ds + "T00:00:00");
  return `${String(d.getDate()).padStart(2,'0')}.${String(d.getMonth()+1).padStart(2,'0')}.${d.getFullYear()}`;
}

function getPredigerHistory(predigerId, planung) {
  const history = [];
  Object.entries(planung).forEach(([key, pid]) => {
    if (pid !== predigerId) return;
    const match = key.match(/^(\d{4}-\d{2}-\d{2})_(.+)$/);
    if (!match) return;
    const [, dateStr, slotId] = match;
    const date = new Date(dateStr + "T00:00:00");
    history.push({ dateStr, slotId, date, label: getSlotLabelFromId(slotId, date.getMonth() + 1) });
  });
  return history.sort((a, b) => b.dateStr.localeCompare(a.dateStr));
}

const C = {
  bg:"#FAF7F2", bgCard:"#FFFFFF", bgMuted:"#F3EDE3",
  primary:"#7B3535", primaryLight:"#9E4E4E", primaryDark:"#5C2828",
  accent:"#B8860B", green:"#4A6741",
  text:"#2C1F1F", textMuted:"#7A6A6A", textLight:"#B09090",
  border:"#E8DDD5", white:"#FFFFFF",
};

const S = {
  iconBtn:{ background:"none", border:"none", cursor:"pointer", padding:6, borderRadius:8, display:"flex", alignItems:"center", justifyContent:"center" },
  gdCard:{ display:"block", width:"100%", background:C.bgCard, borderRadius:10, padding:"10px 12px", marginBottom:7, border:`1px solid ${C.border}`, cursor:"pointer", textAlign:"left", boxShadow:"0 1px 3px rgba(0,0,0,0.04)" },
  listItem:{ display:"flex", alignItems:"center", gap:12, width:"100%", padding:"11px 16px", background:C.white, border:"none", cursor:"pointer", textAlign:"left" },
  ava:{ width:36, height:36, borderRadius:18, background:C.bgMuted, display:"flex", alignItems:"center", justifyContent:"center", fontSize:13, fontWeight:700, color:C.primary, flexShrink:0, fontFamily:"Georgia,serif" },
  infoCard:{ background:C.bgCard, borderRadius:10, padding:"12px 14px", marginBottom:12, border:`1px solid ${C.border}` },
  toggleA:{ background:C.primary, color:C.white, border:"none", borderRadius:16, padding:"5px 14px", fontSize:12, fontWeight:700, cursor:"pointer" },
  toggleI:{ background:C.bgMuted, color:C.textMuted, border:"none", borderRadius:16, padding:"5px 14px", fontSize:12, cursor:"pointer" },
  pill:{ background:"rgba(255,255,255,0.15)", borderRadius:10, padding:"8px 10px", flex:1, textAlign:"center" },
  btn:{ background:C.primary, color:C.white, border:"none", borderRadius:10, padding:"12px", fontSize:14, fontWeight:700, cursor:"pointer", fontFamily:"Georgia,serif", width:"100%" },
};

const Icon = ({ name, size=22, color=C.text, style:st }) => {
  const p = {
    calendar:<><rect x="3" y="4" width="18" height="18" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><line x1="16" y1="2" x2="16" y2="6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><line x1="8" y1="2" x2="8" y2="6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><line x1="3" y1="10" x2="21" y2="10" stroke="currentColor" strokeWidth="1.6"/></>,
    people:<><circle cx="9" cy="7" r="3" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M3 21v-2a5 5 0 0 1 5-5h2a5 5 0 0 1 5 5v2" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M16 3.13a4 4 0 0 1 0 7.75M21 21v-2a4 4 0 0 0-3-3.87" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
    chart:<><line x1="18" y1="20" x2="18" y2="10" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="12" y1="20" x2="12" y2="4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="6" y1="20" x2="6" y2="14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></>,
    settings:<><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" fill="none" stroke="currentColor" strokeWidth="1.8"/></>,
    chevL:<path d="M15 18l-6-6 6-6" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>,
    chevR:<path d="M9 18l6-6-6-6" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>,
    x:<><line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></>,
    check:<path d="M5 13l4 4L19 7" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>,
    phone:<path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.81 19.79 19.79 0 01.06 1.18 2 2 0 012.03 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z" fill="none" stroke="currentColor" strokeWidth="1.8"/>,
    mail:<><rect x="2" y="4" width="20" height="16" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M2 7l10 7 10-7" fill="none" stroke="currentColor" strokeWidth="1.8"/></>,
    plus:<><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></>,
    search:<><circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M21 21l-4.35-4.35" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
    trash:<><polyline points="3 6 5 6 21 6" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M10 11v6M14 11v6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
    excel:<><rect x="3" y="3" width="18" height="18" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M7 8l3 4-3 4M13 8h4M13 12h4M13 16h4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
    pdf:<><rect x="3" y="3" width="18" height="18" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M7 8h4a2 2 0 010 4H7v4M7 12h4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
    cloud:<><path d="M18 10h-1.26A8 8 0 109 20h9a5 5 0 000-10z" fill="none" stroke="currentColor" strokeWidth="1.8"/></>,
    week:<><rect x="3" y="4" width="18" height="18" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><line x1="3" y1="10" x2="21" y2="10" stroke="currentColor" strokeWidth="1.5"/><line x1="9" y1="4" x2="9" y2="22" stroke="currentColor" strokeWidth="1.3"/></>,
    month:<><rect x="3" y="4" width="18" height="18" rx="2" fill="none" stroke="currentColor" strokeWidth="1.8"/><line x1="3" y1="10" x2="21" y2="10" stroke="currentColor" strokeWidth="1.5"/><line x1="8" y1="14" x2="8" y2="18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><line x1="12" y1="14" x2="12" y2="18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><line x1="16" y1="14" x2="16" y2="18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></>,
  };
  return <svg width={size} height={size} viewBox="0 0 24 24" style={{ color, flexShrink:0, ...st }}>{p[name]}</svg>;
};

const ini = n => n.split(" ").map(x=>x[0]).join("").slice(0,2).toUpperCase();

// ─── App State with Firebase ──────────────────────────────────────
function useAppState() {
  const [prediger, setPrediger] = useState(() => loadPrediger());
  const [planung, setPlanung] = useState(() => {
    const s = localStorage.getItem("planung_v3");
    if (s) try { return JSON.parse(s); } catch(e) {}
    return null;
  });
  const [weekOffset, setWeekOffset] = useState(0);
  const [monthOffset, setMonthOffset] = useState(0);

  useEffect(() => {
    if (FB.ready()) {
      const u1 = FB.onPrediger(list => { if (list.length) { setPrediger(list); savePrediger(list); } });
      const u2 = FB.onPlanung(data => { setPlanung(data); localStorage.setItem("planung_v3", JSON.stringify(data)); });
      // Migrate local data if Firebase is empty
      const localPl = JSON.parse(localStorage.getItem("planung_v3") || "{}");
      FB.migrateFromLocal(loadPrediger(), localPl);
      return () => { u1(); u2(); };
    } else {
      if (!planung) {
        const p = loadPrediger();
        const pl = createInitialPlanung(p);
        setPlanung(pl);
        localStorage.setItem("planung_v3", JSON.stringify(pl));
      }
    }
  }, []);

  useEffect(() => { if (planung && !FB.ready()) localStorage.setItem("planung_v3", JSON.stringify(planung)); }, [planung]);
  useEffect(() => { if (!FB.ready()) savePrediger(prediger); }, [prediger]);

  const assignPrediger = (ds, slotId, pid) => {
    const key = `${ds}_${slotId}`;
    setPlanung(prev => { const n = {...prev}; if (pid == null) delete n[key]; else n[key] = pid; return n; });
    if (FB.ready()) FB.setSlot(key, pid);
  };
  const addPrediger = neu => {
    const id = Math.max(0, ...prediger.map(p=>p.id)) + 1;
    const p = { ...neu, id };
    setPrediger(prev => [...prev, p]);
    if (FB.ready()) FB.addPrediger(p);
    return p;
  };
  const deletePrediger = id => {
    setPrediger(prev => prev.filter(p => p.id !== id));
    setPlanung(prev => { const n = {...prev}; Object.keys(n).forEach(k => { if (n[k]===id) delete n[k]; }); return n; });
    if (FB.ready()) FB.removePrediger(id);
  };
  const deleteAllData = async () => {
    setPrediger([]);
    setPlanung({});
    localStorage.removeItem("planung_v3");
    savePrediger([]);
    if (FB.ready()) await FB.removeAllData();
  };

  return { prediger, planung:planung||{}, weekOffset, setWeekOffset, monthOffset, setMonthOffset, assignPrediger, addPrediger, deletePrediger, deleteAllData };
}

// ─── Shared helpers ───────────────────────────────────────────────
function TagKarten({ date, planung, prediger, onAssign }) {
  const ds = date.toISOString().slice(0,10);
  const slots = getSlotsForDate(date);
  if (!slots.length) return null;
  const isToday = ds === new Date().toISOString().slice(0,10);
  return (
    <div style={{ marginBottom:12 }}>
      <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:6 }}>
        <span style={{ fontSize:12, fontWeight:700, color:C.textMuted, textTransform:"uppercase", letterSpacing:"0.05em" }}>
          {WOCHENTAGE[date.getDay()]}, {date.getDate()}. {MONATE_KURZ[date.getMonth()]}
        </span>
        {isToday && <span style={{ fontSize:10, background:C.accent, color:C.white, borderRadius:4, padding:"1px 6px", fontWeight:700 }}>Heute</span>}
      </div>
      {slots.map(slot => {
        const pid = planung[`${ds}_${slot.id}`];
        const p = prediger.find(x => x.id === pid);
        return (
          <button key={slot.id} onClick={() => onAssign(ds, slot)} style={{ ...S.gdCard, borderLeft:`4px solid ${slot.farbe}` }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:C.text, fontFamily:"Georgia,serif" }}>{slot.label}</div>
                <div style={{ fontSize:11, color:C.textMuted, marginTop:2 }}>{slot.kurz}</div>
              </div>
              <div style={{ textAlign:"right" }}>
                {p ? (<div>
                  <div style={{ fontSize:13, fontWeight:600, color:C.primary }}>{p.name.split(" ")[0]}</div>
                  <div style={{ fontSize:11, color:C.textMuted }}>{p.name.split(" ").slice(1).join(" ")}</div>
                  {p.schicht && <div style={{ fontSize:10, color:C.accent, fontWeight:700 }}>⚡ Schicht</div>}
                </div>) : <span style={{ fontSize:12, color:"#C0A0A0", fontStyle:"italic" }}>— offen —</span>}
              </div>
            </div>
          </button>
        );
      })}
    </div>
  );
}

// ─── Planung Screens ──────────────────────────────────────────────
function WochenFull({ planung, prediger, weekOffset, setWeekOffset, onAssign }) {
  const days = getWeekDays(weekOffset);
  const mon = days[0]; const sun = days[6];
  const kw = `KW ${getKW(mon)} · ${mon.getDate()}. ${MONATE_KURZ[mon.getMonth()]} – ${sun.getDate()}. ${MONATE_KURZ[sun.getMonth()]}`;
  const rel = days.filter(d => getSlotsForDate(d).length > 0);
  return (<>
    <div style={{ background:C.primary, padding:"0 16px 12px", flexShrink:0 }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
        <button onClick={() => setWeekOffset(w=>w-1)} style={S.iconBtn}><Icon name="chevL" size={20} color={C.white}/></button>
        <div style={{ textAlign:"center" }}>
          <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:14, fontWeight:700 }}>Wochenplanung</div>
          <div style={{ color:"rgba(255,255,255,0.75)", fontSize:11, marginTop:1 }}>{kw}</div>
        </div>
        <button onClick={() => setWeekOffset(w=>w+1)} style={S.iconBtn}><Icon name="chevR" size={20} color={C.white}/></button>
      </div>
      {weekOffset !== 0 && <div style={{ textAlign:"center", marginTop:6 }}>
        <button onClick={() => setWeekOffset(0)} style={{ background:"rgba(255,255,255,0.2)", border:"none", color:"white", borderRadius:12, padding:"3px 12px", fontSize:11, cursor:"pointer" }}>Aktuelle Woche</button>
      </div>}
    </div>
    <div style={{ flex:1, overflowY:"auto", padding:"12px 14px 8px", background:C.bg }}>
      {rel.length === 0 ? <div style={{ textAlign:"center", color:C.textMuted, marginTop:40 }}>Keine Gottesdienste</div>
        : rel.map(d => <TagKarten key={d.toISOString()} date={d} planung={planung} prediger={prediger} onAssign={onAssign}/>)}
      <div style={{ height:8 }}/>
    </div>
  </>);
}

function MonatsFull({ planung, prediger, monthOffset, setMonthOffset, onAssign }) {
  const ref = new Date(new Date().getFullYear(), new Date().getMonth() + monthOffset);
  const yr = ref.getFullYear(); const mo = ref.getMonth();
  const rel = getMonthDays(yr, mo).filter(d => getSlotsForDate(d).length > 0);
  let total=0, offen=0;
  rel.forEach(d => { const ds=d.toISOString().slice(0,10); getSlotsForDate(d).forEach(sl => { total++; if (!planung[`${ds}_${sl.id}`]) offen++; }); });
  return (<>
    <div style={{ background:C.primary, padding:"0 16px 12px", flexShrink:0 }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
        <button onClick={() => setMonthOffset(m=>m-1)} style={S.iconBtn}><Icon name="chevL" size={20} color={C.white}/></button>
        <div style={{ textAlign:"center" }}>
          <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:14, fontWeight:700 }}>{MONATE[mo]} {yr}</div>
          <div style={{ color:"rgba(255,255,255,0.7)", fontSize:11, marginTop:1 }}>Di: {getDiTyp(mo+1)} · Fr: {getFrTyp(mo+1)}</div>
        </div>
        <button onClick={() => setMonthOffset(m=>m+1)} style={S.iconBtn}><Icon name="chevR" size={20} color={C.white}/></button>
      </div>
      <div style={{ display:"flex", gap:8 }}>
        <div style={S.pill}><div style={{ fontSize:15, fontWeight:700, color:C.white }}>{total}</div><div style={{ fontSize:10, color:"rgba(255,255,255,0.7)" }}>Predigten</div></div>
        <div style={S.pill}><div style={{ fontSize:15, fontWeight:700, color:offen>0?"#FFD080":"#A0FFB0" }}>{offen}</div><div style={{ fontSize:10, color:"rgba(255,255,255,0.7)" }}>Offen</div></div>
        <div style={S.pill}><div style={{ fontSize:15, fontWeight:700, color:C.white }}>{total-offen}</div><div style={{ fontSize:10, color:"rgba(255,255,255,0.7)" }}>Besetzt</div></div>
      </div>
    </div>
    <div style={{ flex:1, overflowY:"auto", padding:"12px 14px 8px", background:C.bg }}>
      {rel.map(d => <TagKarten key={d.toISOString()} date={d} planung={planung} prediger={prediger} onAssign={onAssign}/>)}
      <div style={{ height:8 }}/>
    </div>
  </>);
}

function PlanungFull(props) {
  const [view, setView] = useState("woche");
  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100%", overflow:"hidden" }}>
      <div style={{ background:C.primary, padding:"12px 16px 10px", flexShrink:0 }}>
        <div style={{ display:"flex", gap:6 }}>
          {[["woche","week","Woche"],["monat","month","Monat"]].map(([id,icon,lbl]) => (
            <button key={id} onClick={() => setView(id)} style={{ ...(view===id ? S.toggleA : {...S.toggleI, background:"rgba(255,255,255,0.15)", color:"rgba(255,255,255,0.75)", border:"none"}), display:"flex", alignItems:"center", gap:5, fontSize:12 }}>
              <Icon name={icon} size={13} color={view===id ? C.white : "rgba(255,255,255,0.75)"}/>
              {lbl}
            </button>
          ))}
        </div>
      </div>
      <div style={{ flex:1, display:"flex", flexDirection:"column", overflow:"hidden" }}>
        {view==="woche" ? <WochenFull {...props}/> : <MonatsFull {...props}/>}
      </div>
    </div>
  );
}

// ─── Prediger Screen ──────────────────────────────────────────────
function PredigerScreen({ prediger, planung, onAdd, onDelete }) {
  const [suche, setSuche] = useState("");
  const [selectedId, setSelectedId] = useState(null);
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ name:"", tel:"", email:"", schicht:false });
  const stats = berechneStatistik(planung, prediger);

  const gefiltert = prediger.filter(p => p.name.toLowerCase().includes(suche.toLowerCase())).sort((a,b) => a.name.localeCompare(b.name));
  const selected = prediger.find(p => p.id === selectedId);

  // Detail
  if (selected) {
    const st = stats[selected.id] || { count:0, letzterTermin:null };
    const history = getPredigerHistory(selected.id, planung);
    return (
      <div style={{ display:"flex", flexDirection:"column", height:"100%" }}>
        <div style={{ background:C.primary, padding:"14px 16px 16px", flexShrink:0 }}>
          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:10 }}>
            <button onClick={() => setSelectedId(null)} style={S.iconBtn}><Icon name="chevL" size={20} color={C.white}/></button>
            <button onClick={() => { if (window.confirm(`${selected.name} wirklich löschen?`)) { onDelete(selected.id); setSelectedId(null); } }} style={S.iconBtn}><Icon name="trash" size={18} color="rgba(255,180,180,0.9)"/></button>
          </div>
          <div style={{ display:"flex", alignItems:"center", gap:12 }}>
            <div style={{ ...S.ava, width:44, height:44, borderRadius:22, background:"rgba(255,255,255,0.2)", color:C.white, fontSize:16 }}>{ini(selected.name)}</div>
            <div>
              <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:16, fontWeight:700 }}>{selected.name}</div>
              {selected.schicht && <div style={{ fontSize:11, color:"rgba(255,220,100,0.9)", fontWeight:700, marginTop:2 }}>⚡ Schichtarbeiter</div>}
            </div>
          </div>
        </div>
        <div style={{ flex:1, overflowY:"auto", padding:"14px 14px" }}>
          {(selected.tel || selected.email) && <div style={S.infoCard}>
            {selected.tel && <div style={{ display:"flex", alignItems:"center", gap:10, paddingBottom:8, marginBottom:8, borderBottom:`1px solid ${C.border}` }}><Icon name="phone" size={15} color={C.primary}/><span style={{ fontSize:14 }}>{selected.tel}</span></div>}
            {selected.email && <div style={{ display:"flex", alignItems:"center", gap:10 }}><Icon name="mail" size={15} color={C.primary}/><span style={{ fontSize:13, color:C.textMuted }}>{selected.email}</span></div>}
          </div>}
          {/* Statistik */}
          <div style={S.infoCard}>
            <div style={{ fontSize:11, fontWeight:700, color:C.textMuted, textTransform:"uppercase", letterSpacing:"0.06em", marginBottom:10 }}>Statistik</div>
            <div style={{ display:"flex", gap:12, alignItems:"center", marginBottom: history.length ? 12 : 0 }}>
              <div style={{ background:C.bgMuted, borderRadius:10, padding:"10px 16px", textAlign:"center", minWidth:72 }}>
                <div style={{ fontSize:26, fontWeight:700, color:C.primary, fontFamily:"Georgia,serif" }}>{st.count}</div>
                <div style={{ fontSize:11, color:C.textMuted }}>Predigten</div>
              </div>
              <div>
                <div style={{ fontSize:12, color:C.textMuted, marginBottom:2 }}>Letzter Termin</div>
                <div style={{ fontSize:13, fontWeight:600, color:C.text }}>{formatDatum(st.letzterTermin)}</div>
              </div>
            </div>
            {/* Verlauf */}
            {history.length > 0 && <>
              <div style={{ fontSize:11, fontWeight:700, color:C.textMuted, textTransform:"uppercase", letterSpacing:"0.05em", marginBottom:8, borderTop:`1px solid ${C.border}`, paddingTop:10 }}>Predigtverlauf</div>
              {history.map((h,i) => (
                <div key={i} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", paddingBottom:7, marginBottom:7, borderBottom: i < history.length-1 ? `1px solid ${C.border}` : "none" }}>
                  <div>
                    <div style={{ fontSize:12, fontWeight:600, color:C.text }}>{h.label}</div>
                    <div style={{ fontSize:11, color:C.textMuted }}>{WOCHENTAGE[h.date.getDay()]}</div>
                  </div>
                  <div style={{ fontSize:12, color:C.primary, fontWeight:600, textAlign:"right" }}>
                    {String(h.date.getDate()).padStart(2,'0')}.{String(h.date.getMonth()+1).padStart(2,'0')}.{h.date.getFullYear()}
                  </div>
                </div>
              ))}
            </>}
          </div>
        </div>
      </div>
    );
  }

  // Hinzufügen
  if (showAdd) {
    return (
      <div style={{ display:"flex", flexDirection:"column", height:"100%" }}>
        <div style={{ background:C.primary, padding:"14px 16px 16px", flexShrink:0 }}>
          <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
            <button onClick={() => setShowAdd(false)} style={S.iconBtn}><Icon name="x" size={20} color={C.white}/></button>
            <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:15, fontWeight:700 }}>Neuer Prediger</div>
            <div style={{ width:32 }}/>
          </div>
        </div>
        <div style={{ flex:1, overflowY:"auto", padding:"16px" }}>
          {[["Name *","name","text","Vorname Nachname"],["Telefon","tel","tel","0172 …"],["E-Mail","email","email","name@kirche.de"]].map(([lbl,key,type,ph]) => (
            <div key={key} style={{ marginBottom:14 }}>
              <div style={{ fontSize:12, fontWeight:700, color:C.textMuted, marginBottom:4 }}>{lbl}</div>
              <input value={form[key]} onChange={e => setForm(f=>({...f,[key]:e.target.value}))} placeholder={ph} type={type}
                style={{ width:"100%", border:`1.5px solid ${C.border}`, borderRadius:8, padding:"9px 12px", fontSize:14, outline:"none", background:C.bgCard }}/>
            </div>
          ))}
          <div style={{ marginBottom:20 }}>
            <div style={{ fontSize:12, fontWeight:700, color:C.textMuted, marginBottom:8 }}>Schichtarbeiter</div>
            <button onClick={() => setForm(f=>({...f,schicht:!f.schicht}))} style={{ display:"flex", alignItems:"center", gap:10, background:"none", border:"none", cursor:"pointer", padding:0 }}>
              <div style={{ width:44, height:24, borderRadius:12, background:form.schicht ? C.primary : C.border, position:"relative", transition:"background 0.2s" }}>
                <div style={{ position:"absolute", top:2, left:form.schicht?22:2, width:20, height:20, borderRadius:10, background:"white", transition:"left 0.2s", boxShadow:"0 1px 3px rgba(0,0,0,0.2)" }}/>
              </div>
              <span style={{ fontSize:13, color:form.schicht?C.primary:C.textMuted, fontWeight:form.schicht?700:400 }}>{form.schicht?"Ja":"Nein"}</span>
            </button>
          </div>
          <button onClick={() => { if (!form.name.trim()) return; onAdd(form); setShowAdd(false); setForm({name:"",tel:"",email:"",schicht:false}); }}
            disabled={!form.name.trim()}
            style={{ ...S.btn, opacity:form.name.trim()?1:0.5 }}>Prediger hinzufügen</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100%" }}>
      <div style={{ background:C.primary, padding:"14px 16px 10px", flexShrink:0 }}>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:10 }}>
          <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:15, fontWeight:700 }}>Prediger ({prediger.length})</div>
          <button onClick={() => setShowAdd(true)} style={{ ...S.iconBtn, background:"rgba(255,255,255,0.2)", borderRadius:20, padding:"5px 10px", gap:4 }}>
            <Icon name="plus" size={16} color={C.white}/>
            <span style={{ fontSize:12, color:C.white, fontWeight:600 }}>Neu</span>
          </button>
        </div>
        <div style={{ display:"flex", alignItems:"center", background:"rgba(255,255,255,0.15)", borderRadius:10, padding:"7px 10px", gap:8 }}>
          <Icon name="search" size={15} color="rgba(255,255,255,0.7)"/>
          <input value={suche} onChange={e => setSuche(e.target.value)} placeholder="Name suchen…"
            style={{ background:"none", border:"none", outline:"none", color:C.white, fontSize:14, flex:1 }}/>
        </div>
      </div>
      <div style={{ flex:1, overflowY:"auto" }}>
        {gefiltert.map(p => {
          const st = stats[p.id] || { count:0 };
          return (
            <button key={p.id} onClick={() => setSelectedId(p.id)} style={{ ...S.listItem, borderBottom:`1px solid ${C.border}` }}>
              <div style={S.ava}>{ini(p.name)}</div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:600, color:C.text }}>{p.name}</div>
                <div style={{ fontSize:11, color:C.textMuted, marginTop:1 }}>{st.count} Predigt{st.count!==1?"en":""}  {p.schicht?"· ⚡ Schicht":""}</div>
              </div>
              <Icon name="chevR" size={16} color={C.textLight}/>
            </button>
          );
        })}
        <div style={{ height:8 }}/>
      </div>
    </div>
  );
}

// ─── Statistik Screen ─────────────────────────────────────────────
function StatistikScreen({ planung, prediger }) {
  const stats = berechneStatistik(planung, prediger);
  const [sort, setSort] = useState("count");
  const sorted = [...prediger].map(p=>({...p,...(stats[p.id]||{count:0,letzterTermin:null})}))
    .sort((a,b) => sort==="count" ? b.count-a.count : a.name.localeCompare(b.name));
  const max = Math.max(...sorted.map(p=>p.count),1);
  const gesamt = sorted.reduce((s,p)=>s+p.count,0);
  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100%" }}>
      <div style={{ background:C.primary, padding:"14px 16px 12px", flexShrink:0 }}>
        <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:15, fontWeight:700, marginBottom:10 }}>Statistik</div>
        <div style={{ display:"flex", gap:8 }}>
          <div style={S.pill}><span style={{ fontSize:17, fontWeight:700, color:C.white }}>{gesamt}</span><span style={{ fontSize:10, color:"rgba(255,255,255,0.7)", display:"block" }}>Predigten</span></div>
          <div style={S.pill}><span style={{ fontSize:17, fontWeight:700, color:C.white }}>{sorted.filter(p=>p.count>0).length}</span><span style={{ fontSize:10, color:"rgba(255,255,255,0.7)", display:"block" }}>aktive Prediger</span></div>
          <div style={S.pill}><span style={{ fontSize:17, fontWeight:700, color:C.white }}>{prediger.length}</span><span style={{ fontSize:10, color:"rgba(255,255,255,0.7)", display:"block" }}>gesamt</span></div>
        </div>
      </div>
      <div style={{ display:"flex", padding:"10px 14px 6px", gap:8, flexShrink:0, background:C.bg }}>
        <button onClick={()=>setSort("count")} style={sort==="count"?S.toggleA:S.toggleI}>Häufigkeit</button>
        <button onClick={()=>setSort("name")} style={sort==="name"?S.toggleA:S.toggleI}>A–Z</button>
      </div>
      <div style={{ flex:1, overflowY:"auto", padding:"4px 14px 8px", background:C.bg }}>
        {sorted.map(p => (
          <div key={p.id} style={{ marginBottom:9 }}>
            <div style={{ display:"flex", justifyContent:"space-between", marginBottom:3 }}>
              <span style={{ fontSize:13, fontWeight:600, color:C.text }}>{p.name}</span>
              <span style={{ fontSize:13, fontWeight:700, color:p.count>0?C.primary:C.textLight }}>{p.count}×</span>
            </div>
            <div style={{ height:6, background:C.bgMuted, borderRadius:4, overflow:"hidden" }}>
              <div style={{ height:"100%", width:`${(p.count/max)*100}%`, background:`linear-gradient(90deg,${C.primary},${C.primaryLight})`, borderRadius:4 }}/>
            </div>
          </div>
        ))}
        <div style={{ height:8 }}/>
      </div>
    </div>
  );
}

// ─── Settings Screen ──────────────────────────────────────────────
function SettingsScreen({ planung, prediger, onDeleteAll, onSetupFirebase }) {
  const fbOk = FB.ready();
  const SettingRow = ({ icon, title, sub, onClick, danger, right }) => (
    <button onClick={onClick} style={{ ...S.listItem, borderBottom:`1px solid ${C.border}`, padding:"13px 16px" }}>
      <div style={{ width:36, height:36, borderRadius:18, background:danger?"#FFF0F0":C.bgMuted, display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>
        <Icon name={icon} size={18} color={danger?"#C44":C.primary}/>
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:14, fontWeight:600, color:danger?"#C44":C.text }}>{title}</div>
        {sub && <div style={{ fontSize:11, color:C.textMuted, marginTop:1 }}>{sub}</div>}
      </div>
      {right || <Icon name="chevR" size={16} color={C.textLight}/>}
    </button>
  );
  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100%" }}>
      <div style={{ background:C.primary, padding:"14px 16px 14px", flexShrink:0 }}>
        <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:15, fontWeight:700 }}>Einstellungen</div>
      </div>
      <div style={{ flex:1, overflowY:"auto", background:C.bg }}>
        {/* Cloud */}
        <div style={{ padding:"12px 14px 4px" }}><span style={{ fontSize:11, fontWeight:700, color:C.textMuted, textTransform:"uppercase", letterSpacing:"0.06em" }}>Cloud-Synchronisation</span></div>
        <div style={{ background:C.white }}>
          <SettingRow icon="cloud" title="Firebase" sub={fbOk ? "✓ Verbunden – Daten werden synchronisiert" : "Nicht eingerichtet – nur lokale Speicherung"} onClick={onSetupFirebase}
            right={<span style={{ fontSize:11, fontWeight:700, color:fbOk?"#4A6741":"#C0A0A0", background:fbOk?"#EEF7EC":"#F5EDEA", borderRadius:10, padding:"3px 8px" }}>{fbOk?"Aktiv":"Inaktiv"}</span>}/>
        </div>
        {/* Export */}
        <div style={{ padding:"12px 14px 4px" }}><span style={{ fontSize:11, fontWeight:700, color:C.textMuted, textTransform:"uppercase", letterSpacing:"0.06em" }}>Export</span></div>
        <div style={{ background:C.white }}>
          <SettingRow icon="excel" title="Als Excel exportieren" sub={`${Object.keys(planung).filter(k=>planung[k]).length} Einträge · ${prediger.length} Prediger`} onClick={() => exportExcel(planung, prediger)}/>
          <SettingRow icon="pdf" title="Als PDF drucken" sub="Planungsübersicht zum Drucken" onClick={() => exportPDF(planung, prediger)}/>
        </div>
        {/* Daten */}
        <div style={{ padding:"12px 14px 4px" }}><span style={{ fontSize:11, fontWeight:700, color:C.textMuted, textTransform:"uppercase", letterSpacing:"0.06em" }}>Datenverwaltung</span></div>
        <div style={{ background:C.white }}>
          <SettingRow icon="trash" title="Alle Daten löschen" sub="Alle Prediger und Planung unwiderruflich löschen" onClick={onDeleteAll} danger/>
        </div>
        {/* Info */}
        <div style={{ padding:"20px 16px", textAlign:"center" }}>
          <div style={{ fontSize:12, color:C.textLight }}>Predigerplanung · Version 3.0</div>
        </div>
      </div>
    </div>
  );
}

// ─── Prediger-Wahl Modal ──────────────────────────────────────────
function PredigerWahlModal({ ds, slot, planung, prediger, onSelect, onClose }) {
  const [suche, setSuche] = useState("");
  const stats = berechneStatistik(planung, prediger);
  const cur = planung[`${ds}_${slot.id}`];
  const date = new Date(ds + "T00:00:00");
  const gef = prediger.filter(p => p.name.toLowerCase().includes(suche.toLowerCase()))
    .sort((a,b) => (stats[a.id]?.count||0) - (stats[b.id]?.count||0));
  return (
    <div style={{ position:"absolute", inset:0, zIndex:50, display:"flex", flexDirection:"column", background:C.bg }}>
      <div style={{ background:C.primary, padding:"14px 16px 12px", flexShrink:0 }}>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
          <div>
            <div style={{ color:C.white, fontFamily:"Georgia,serif", fontSize:14, fontWeight:700 }}>{slot.label}</div>
            <div style={{ fontSize:11, color:"rgba(255,255,255,0.7)", marginTop:1 }}>{WOCHENTAGE[date.getDay()]}, {date.getDate()}. {MONATE_KURZ[date.getMonth()]}</div>
          </div>
          <button onClick={onClose} style={S.iconBtn}><Icon name="x" size={20} color={C.white}/></button>
        </div>
        <div style={{ display:"flex", alignItems:"center", background:"rgba(255,255,255,0.15)", borderRadius:10, padding:"7px 10px", gap:8 }}>
          <Icon name="search" size={15} color="rgba(255,255,255,0.7)"/>
          <input autoFocus value={suche} onChange={e => setSuche(e.target.value)} placeholder="Prediger suchen…"
            style={{ background:"none", border:"none", outline:"none", color:C.white, fontSize:14, flex:1 }}/>
        </div>
      </div>
      <button onClick={() => onSelect(null)} style={{ ...S.listItem, borderBottom:`1px solid ${C.border}` }}>
        <div style={{ ...S.ava, background:C.bgMuted, color:C.textMuted }}>–</div>
        <div style={{ flex:1 }}><div style={{ fontSize:14, color:C.textMuted, fontStyle:"italic" }}>Kein Prediger (offen lassen)</div></div>
        {!cur && <Icon name="check" size={16} color={C.primary}/>}
      </button>
      <div style={{ flex:1, overflowY:"auto" }}>
        {gef.map(p => {
          const st = stats[p.id]||{count:0};
          const isCur = p.id === cur;
          return (
            <button key={p.id} onClick={() => onSelect(p.id)} style={{ ...S.listItem, borderBottom:`1px solid ${C.border}`, background:isCur?"#FFF5F5":C.white }}>
              <div style={{ ...S.ava, background:isCur?C.primary:C.bgMuted, color:isCur?C.white:C.primary }}>{ini(p.name)}</div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:isCur?700:500, color:C.text }}>{p.name}</div>
                <div style={{ fontSize:11, color:C.textMuted }}>{st.count} Predigt{st.count!==1?"en":""}{p.schicht?" · ⚡ Schicht":""}</div>
              </div>
              {isCur && <Icon name="check" size={16} color={C.primary}/>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─── Bottom Nav ───────────────────────────────────────────────────
function BottomNav({ active, setActive }) {
  return (
    <div style={{ display:"flex", background:C.white, borderTop:`1px solid ${C.border}`, flexShrink:0 }}>
      {[["planung","calendar","Planung"],["prediger","people","Prediger"],["statistik","chart","Statistik"],["settings","settings","Einstellungen"]].map(([id,icon,lbl]) => (
        <button key={id} onClick={() => setActive(id)} style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", padding:"8px 4px 6px", background:"none", border:"none", cursor:"pointer", gap:3 }}>
          <Icon name={icon} size={20} color={active===id?C.primary:C.textLight}/>
          <span style={{ fontSize:9, fontWeight:active===id?700:500, color:active===id?C.primary:C.textLight }}>{lbl}</span>
        </button>
      ))}
    </div>
  );
}

// ─── App Root ─────────────────────────────────────────────────────
function PredigerApp() {
  const [authed, setAuthed] = useState(() => sessionStorage.getItem("auth_v1") === "1");
  const [showFbSetup, setShowFbSetup] = useState(() => !FB.ready() && !localStorage.getItem("fb_skipped"));
  const [screen, setScreen] = useState(() => localStorage.getItem("screen_v3") || "planung");
  const { prediger, planung, weekOffset, setWeekOffset, monthOffset, setMonthOffset, assignPrediger, addPrediger, deletePrediger, deleteAllData } = useAppState();
  const [modal, setModal] = useState(null);

  useEffect(() => { localStorage.setItem("screen_v3", screen); }, [screen]);

  const handleDeleteAll = () => {
    if (window.confirm("Wirklich ALLE Daten löschen?\n\nAlle Prediger und die gesamte Planung werden unwiderruflich gelöscht.")) {
      deleteAllData();
    }
  };

  if (!authed) return <AuthScreen onAuth={() => setAuthed(true)}/>;
  if (showFbSetup) return <FirebaseSetupScreen onDone={() => setShowFbSetup(false)} onSkip={() => { localStorage.setItem("fb_skipped","1"); setShowFbSetup(false); }}/>;

  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100%", background:C.bg, fontFamily:"system-ui,-apple-system,sans-serif", position:"relative", overflow:"hidden" }}>
      <div style={{ flex:1, overflow:"hidden", position:"relative" }}>
        {screen==="planung" && <PlanungFull planung={planung} prediger={prediger} weekOffset={weekOffset} setWeekOffset={setWeekOffset} monthOffset={monthOffset} setMonthOffset={setMonthOffset} onAssign={(ds,slot) => setModal({ds,slot})}/>}
        {screen==="prediger" && <PredigerScreen prediger={prediger} planung={planung} onAdd={addPrediger} onDelete={deletePrediger}/>}
        {screen==="statistik" && <StatistikScreen planung={planung} prediger={prediger}/>}
        {screen==="settings" && <SettingsScreen planung={planung} prediger={prediger} onDeleteAll={handleDeleteAll} onSetupFirebase={() => setShowFbSetup(true)}/>}
        {modal && <PredigerWahlModal ds={modal.ds} slot={modal.slot} planung={planung} prediger={prediger} onSelect={pid => { assignPrediger(modal.ds, modal.slot.id, pid); setModal(null); }} onClose={() => setModal(null)}/>}
      </div>
      <BottomNav active={screen} setActive={setScreen}/>
    </div>
  );
}

Object.assign(window, { PredigerApp });
