const _origFetch = window.fetch;
let _authRedirecting = false;
window.fetch = (url, opts = {}) => {
  const token = localStorage.getItem('authToken');
  if (token && typeof url === 'string' && url.startsWith('/api') && !url.includes('/api/login')) {
    opts.headers = { ...opts.headers, 'Authorization': 'Bearer ' + token };
  }
  return _origFetch(url, opts).then(r => {
    if (r.status === 401 && !_authRedirecting && token && typeof url === 'string' && !url.includes('/api/login') && !url.includes('/api/users') && !url.includes('/api/users/login-list')) {
      _authRedirecting = true;
      localStorage.removeItem('authToken');
      localStorage.removeItem('currentUser');
      window.location.reload();
    }
    return r;
  });
};

const { useState, useEffect, useCallback, useRef } = React;

const CATS = {
  besuchbar:{label:"Besuchbar",icon:"🔥",color:"#F97316"},
  drin:{label:"Drin",icon:"🤩",color:"#3B82F6"},
  geschrieben:{label:"Geschrieben",icon:"💸",color:"#22C55E"},
  abgelehnt:{label:"Abgelehnt",icon:"❌",color:"#EF4444"},
};
const PTYPES=["Freundlich","Reserviert","Direkt","Gesprächig","Skeptisch","Sehr unfreundlich","Offen","Gestresst","Höflich-distanziert","Herzlich"];
const OBJS=["Keine Zeit","Ist verboten","Zentrale hat es nicht erlaubt","Kein Interesse","Haben schon einen Anbieter","Chef/in nicht da","Bitte später wiederkommen","Sonstiges"];

// ═══════ LOGO DOMAINS — hochauflösende Marken-Logos ═══════
// Stand 2026-05-08: Erweitert auf ~110 Marken + Wechsel von Google-Favicon (128px verpixelt)
//                   auf Clearbit Logo API (kostenlos, ohne API-Key, hochauflösende Marken-Logos).
//                   Google-Favicon (size=256) als Fallback wenn Clearbit kein Logo hat.
const LOGO_DOMAINS = {
  // Top-Filialisten
  "Netto":"netto-online.de","Lidl":"lidl.de","ALDI Nord":"aldi-nord.de","ROSSMANN":"rossmann.de",
  "KiK":"kik.de","dm":"dm.de","ALDI SÜD":"aldi-sued.de","TEDi":"tedi.com",
  "Ernsting's family":"ernstings-family.de","McDonald's":"mcdonalds.de","NKD":"nkd.com",
  "Fressnapf":"fressnapf.de","JYSK":"jysk.de","Kaufland":"kaufland.de",
  "Apollo Optik":"apollo.de","Apollo-Optik":"apollo.de",
  "Burger King":"burgerking.de","PENNY":"penny.de","Woolworth":"woolworth.de",
  "Fielmann":"fielmann.de","NORMA":"norma-online.de","Müller":"mueller.de",
  "ATU":"atu.de","Tchibo":"tchibo.de","Getränke Hoffmann":"getraenke-hoffmann.de",
  "OBI":"obi.de","Würth":"wuerth.de","H&M":"hm.com",
  "Steinecke":"baeckerei-steinecke.de","Bäckerei Steinecke":"baeckerei-steinecke.de",
  "MediaMarkt":"mediamarkt.de","Netto Scotty":"netto.de",
  "Douglas":"douglas.de","Bijou Brigitte":"bijou-brigitte.com",
  "Thalia":"thalia.de","Hunkemöller":"hunkemoeller.de","Klier":"klier.de",
  "Takko":"takko.com","Toom":"toom.de","Carglass":"carglass.de",
  "Trinkgut":"trinkgut.de","McPaper":"mcpaper.de","Jeans Fritz":"jeans-fritz.de",
  "New Yorker":"newyorker.de","NEW YORKER":"newyorker.de",
  "Nordsee":"nordsee.com","Nanu-Nana":"nanu-nana.de",
  "BLUME2000":"blume2000.de","Mäc-Geiz":"maec-geiz.de","COMBI":"combi.de",
  "Rituals":"rituals.com","Euromaster":"euromaster.de","BUDNI":"budni.de",
  "K+K":"kk-klaas.de","Bäckerei Steinbrink":"steinbrink.com","BAUHAUS":"bauhaus.info",
  "Shoe4You":"reno.de","Backstube Wünsche":"backstubewuensche.de",
  "Alnatura":"alnatura.de","Kodi":"kodi.de","Hofpfisterei":"hofpfisterei.de",
  "IKEA":"ikea.com","Tom Tailor":"tom-tailor.de","Saturn":"saturn.de",
  "Löwen Play":"loewen-play.de","POCO":"poco.de",
  "Decathlon":"decathlon.de","DECATHLON":"decathlon.de",
  "Wreesmann":"wreesmann.de","Dehner":"dehner.de","Brillux":"brillux.de",
  "Getränkeland":"getraenkeland.de","Sixt":"sixt.de","CAP-Markt":"cap-markt.de",
  "Blumen Risse":"blumen-risse.de","Adler":"adlermode.com","HIT":"hit.de",
  "Zeeman":"zeeman.com","Globus Baumarkt":"globus-baumarkt.de",
  "Hugendubel":"hugendubel.de","Möbel Boss":"moebel-boss.de",
  "ROFU Kinderland":"rofu.de","TÜV Rheinland":"tuv.com",
  "Merzenich":"merzenich-baeckereien.de","BabyOne":"babyone.de",
  "Hussel":"hussel.de","Louis":"louis.de","Foot Locker":"footlocker.de",
  "Tally Weijl":"tally-weijl.com","Hellweg":"hellweg.de",
  "Bäckerei Bachmeier":"baeckerei-bachmeier.de","Wasgau":"wasgau-ag.de",
  "Bonita":"bonita.eu","BrotHaus":"brothaus.de","Globus":"globus.de",
  "Zara":"zara.com","METRO":"metro.de",
  "famila Nordost":"famila-nordost.de","famila Nordwest":"famila-nordwest.de",
  "Hörgeräte Seifert":"hoergeraete-seifert.de","Helbing":"helbing.de",
  "Hilti":"hilti.de","V-Markt":"v-markt.de","OLYMP&HADES":"olymp-hades.de",
  "Reifen Helm":"reifen-helm.de","ONLY":"only.com","Bäcker Schüren":"baeckerschueren.de",
  "Globetrotter":"globetrotter.de","BIRKENSTOCK":"birkenstock.com",
  "Wöhrl":"woehrl.de","Porta Möbel":"porta.de","Driver":"driver.de",
  "expert":"expert.de","Manufactum":"manufactum.de","AWG":"awg-mode.de",
  "Segmüller":"segmueller.de","HERKULES Baumarkt":"herkules-baumarkt.de",
  "Zalando":"zalando.de","VITALIA Reformhaus":"vitalia.de",
  "EDEKA":"edeka.de","REWE":"rewe.de","HORNBACH":"hornbach.de",
  "tegut":"tegut.com","Tegut":"tegut.com",
};

// Hochauflösende Logos: Clearbit primär (kostenlos, ohne API-Key, echte Marken-Logos),
// Google Favicon size=256 als Fallback (besser als 128).
const _logoUrl=(employer)=>{
  const d=LOGO_DOMAINS[employer];
  if(!d) return null;
  return `https://logo.clearbit.com/${d}`;
};
const _logoUrlFallback=(employer)=>{
  const d=LOGO_DOMAINS[employer];
  if(!d) return null;
  return `https://t1.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=http://${d}&size=256`;
};

const Logo = ({ employer, size = 36 }) => {
  const [stage,setStage]=useState(0); // 0=clearbit, 1=fallback favicon, 2=initial-buchstabe
  const url=_logoUrl(employer);
  const fallbackUrl=_logoUrlFallback(employer);
  if(stage===0&&url){
    return <img src={url} width={size} height={size} style={{borderRadius:10,flexShrink:0,objectFit:"contain",background:"white"}} onError={()=>setStage(1)}/>;
  }
  if(stage===1&&fallbackUrl){
    return <img src={fallbackUrl} width={size} height={size} style={{borderRadius:10,flexShrink:0,objectFit:"contain",background:"white"}} onError={()=>setStage(2)}/>;
  }
  return(
    <div style={{width:size,height:size,borderRadius:10,flexShrink:0,background:"#334155",display:"flex",alignItems:"center",justifyContent:"center",fontSize:Math.round(size*0.36),fontWeight:900,color:"#94A3B8",fontFamily:"system-ui"}}>
      {(employer||"?")[0]}
    </div>
  );
};

const logoHTML = (employer, size=28) => {
  const url=_logoUrl(employer);
  const fallbackUrl=_logoUrlFallback(employer);
  const init=(employer||"?")[0];
  const fallbackHTML=`<div style="width:${size}px;height:${size}px;border-radius:7px;background:#334155;display:inline-flex;align-items:center;justify-content:center;font-size:${Math.round(size*0.36)}px;font-weight:900;color:#94A3B8;font-family:system-ui;vertical-align:middle;flex-shrink:0;">${init}</div>`;
  if(url&&fallbackUrl){
    // 2-stufiger Fallback: Clearbit → Google-Favicon-256 → Image verstecken
    return `<img src="${url}" width="${size}" height="${size}" style="border-radius:7px;object-fit:contain;background:white;flex-shrink:0;vertical-align:middle;" onerror="if(this.dataset.fb!=='1'){this.dataset.fb='1';this.src='${fallbackUrl}'}else{this.style.display='none'}"/>`;
  }
  return fallbackHTML;
};


function loadLeaflet(){
  return new Promise(r=>{
    if(window.L){r(window.L);return}
    const l=document.createElement("link");l.rel="stylesheet";l.href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css";document.head.appendChild(l);
    const s=document.createElement("script");s.src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js";s.onload=()=>r(window.L);document.head.appendChild(s);
  });
}

function loadMarkerCluster(){
  return new Promise(r=>{
    if(window.L&&window.L.markerClusterGroup){r();return}
    const l=document.createElement("link");l.rel="stylesheet";l.href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.3/MarkerCluster.css";document.head.appendChild(l);
    const l2=document.createElement("link");l2.rel="stylesheet";l2.href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.3/MarkerCluster.Default.css";document.head.appendChild(l2);
    const s=document.createElement("script");s.src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.3/leaflet.markercluster.min.js";s.onload=()=>r();document.head.appendChild(s);
  });
}

// Plugin für Karten-Rotation (Zwei-Finger-Drehgeste wie bei Google Maps)
function loadLeafletRotate(){
  return new Promise(r=>{
    if(window.__leafletRotateLoaded){r();return}
    const s=document.createElement("script");
    s.src="https://unpkg.com/leaflet-rotate@0.2.8/dist/leaflet-rotate-src.js";
    s.onload=()=>{window.__leafletRotateLoaded=true;r()};
    s.onerror=()=>{console.warn("leaflet-rotate konnte nicht geladen werden");r()};
    document.head.appendChild(s);
  });
}

const haptic=(ms=10)=>{try{navigator.vibrate&&navigator.vibrate(ms)}catch{}};

function App(){
  const [sd,setSd]=useState({});
  const [sel,setSel]=useState(null);
  const [page,setPage]=useState("home");
  const [search,setSearch]=useState("");
  const [fCat,setFCat]=useState("all");
  const [noteText,setNoteText]=useState("");
  const [editNote,setEditNote]=useState(false);
  const [showAV,setShowAV]=useState(false);

  const [uploadModal,setUploadModal]=useState(false);
  const [uploadFile,setUploadFile]=useState(null);
  const [uploadCategory,setUploadCategory]=useState("antrag");
  const [uploading,setUploading]=useState(false);
  const [vS,setVS]=useState("");
  const [vN,setVN]=useState("");
  const [vO,setVO]=useState("");
  const [vC,setVC]=useState("");
  const [mf,setMF]=useState("all");
  const [mapBranchF,setMapBranchF]=useState("all");
  const [mapStoreF,setMapStoreF]=useState("");
  const [saveMsg,setSaveMsg]=useState("");
  const [loaded,setLoaded]=useState(false);
  const [stores,setStores]=useState([]);
  const [storesLoading,setStoresLoading]=useState(false);
  const [userLoc,setUserLoc]=useState({lat:49.4925,lng:9.7744});
  const [radius,setRadius]=useState(25);
  const [gpsEnabled,setGpsEnabled]=useState(true);
  const [gpsStatus,setGpsStatus]=useState("waiting");
  const [gpsError,setGpsError]=useState("");
  const [gpsTime,setGpsTime]=useState(null);
  const [statsPeriod,setStatsPeriod]=useState("W");
  const [planLoc,setPlanLoc]=useState(null);
  const [mapSearch,setMapSearch]=useState("");
  const [searchResults,setSearchResults]=useState([]);
  const [tour,setTour]=useState([]);
  const [allStores,setAllStores]=useState([]);
  const [allStoresLoaded,setAllStoresLoaded]=useState(false);
  const [privacyAccepted,setPrivacyAccepted]=useState(()=>!!localStorage.getItem("privacyAccepted"));
  const [currentUser,setCurrentUser]=useState(()=>{try{return JSON.parse(localStorage.getItem("currentUser"))}catch{return null}});
  // Splash-Screen Förderberatung — TEMPORÄR bei JEDEM Öffnen (zum Justieren)
  // TODO: später wieder auf "1x pro Tag" umschalten:
  //   const t=new Date().toLocaleDateString("de-DE");
  //   return localStorage.getItem("splashShownDate")===t;
  const [splashShownToday,setSplashShownToday]=useState(false);
  // splashRot/splashDragRef entfernt (neues Splash-Design ohne 3D-Karte)
  const [loginPin,setLoginPin]=useState("");
  const [loginError,setLoginError]=useState("");
  const [loginLoading,setLoginLoading]=useState(false);
  const [loginUsers,setLoginUsers]=useState([]);
  const [loginSelUser,setLoginSelUser]=useState(null);
  const [empForm,setEmpForm]=useState({name:"",branche:"",vwl:"",address:"",contact:"",notes:"",website:""});
  const [empInfoOpen,setEmpInfoOpen]=useState("");
  const [fbOpen, setFbOpen] = useState(false);
  const [fbStep, setFbStep] = useState("menu");
  const [fbCat, setFbCat] = useState("");
  const [fbMsg, setFbMsg] = useState("");
  const [fbSent, setFbSent] = useState(false);
  const [fbLoading, setFbLoading] = useState(false);
  const [fbError, setFbError] = useState(false);
  const [docs, setDocs] = useState([]);
  const [docUploading, setDocUploading] = useState(false);
  const [docStore, setDocStore] = useState(null);
  const [docType, setDocType] = useState("antrag");
  const [docFiles, setDocFiles] = useState([]);
  const [docNote, setDocNote] = useState("");
  const [docError, setDocError] = useState("");
  const [docView, setDocView] = useState(null);
  const [empSent,setEmpSent]=useState(false);
  const [profileEdit,setProfileEdit]=useState(false);
  const [profileForm,setProfileForm]=useState({});
  const [adminUsers,setAdminUsers]=useState([]);
  const [showAddUser,setShowAddUser]=useState(false);
  const [newUser,setNewUser]=useState({name:"",pin:"",role:"partner",region:"",phone:"",email:""});
  const [editUserId,setEditUserId]=useState(null);
  const [editUserPin,setEditUserPin]=useState("");
  const [teamStats,setTeamStats]=useState([]);
  const [empSuggestions,setEmpSuggestions]=useState([]);
  const gpsWatchRef=useRef(null);
  const mapRef=useRef(null);
  const mapInst=useRef(null);
  const noteRef=useRef(null);
  const sdRef=useRef(sd);
  sdRef.current=sd;
  const stRef=useRef(null);
  const openStoreRef=useRef(null);
  const [pullY,setPullY]=useState(0);const [refreshing,setRefreshing]=useState(false);const pullRef=useRef({startY:0,active:false});

  // Haversine distance in km
  const getDist=(lat1,lng1,lat2,lng2)=>{
    const R=6371,toRad=x=>x*Math.PI/180;
    const dLat=toRad(lat2-lat1),dLng=toRad(lng2-lng1);
    const a=Math.sin(dLat/2)**2+Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.sin(dLng/2)**2;
    return R*2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
  };
  const distTo=(store)=>{const loc=planLoc||userLoc;return getDist(loc.lat,loc.lng,store.lat,store.lng)};
  const distStr=(store)=>{const d=distTo(store);return d<1?(d*1000).toFixed(0)+" m":d.toFixed(1)+" km";};

  // Get GPS location — starts/stops based on gpsEnabled toggle
  useEffect(()=>{
    if(!gpsEnabled){
      if(gpsWatchRef.current!=null){navigator.geolocation.clearWatch(gpsWatchRef.current);gpsWatchRef.current=null}
      setGpsStatus("off");
      return;
    }
    if(!navigator.geolocation){setGpsStatus("error");return}
    setGpsStatus("waiting");
    const onPos=p=>{
      setUserLoc({lat:p.coords.latitude,lng:p.coords.longitude});
      setGpsStatus("active");
      setGpsTime(new Date());
    };
    const onErr=(e)=>{const msgs={1:"Berechtigung verweigert",2:"Position nicht verfügbar",3:"Zeitüberschreitung"};setGpsError(msgs[e.code]||e.message||"Unbekannt ("+e.code+")");setGpsStatus("error")};
    navigator.geolocation.getCurrentPosition(onPos,onErr,{enableHighAccuracy:true,timeout:15000});
    gpsWatchRef.current=navigator.geolocation.watchPosition(onPos,onErr,{enableHighAccuracy:true,maximumAge:3000});
    return()=>{if(gpsWatchRef.current!=null){navigator.geolocation.clearWatch(gpsWatchRef.current);gpsWatchRef.current=null}};
  },[gpsEnabled]);

  useEffect(()=>{if(!currentUser){setLoaded(true);return}(async()=>{
    const cacheKey=`userdata_${currentUser.id}`;
    try{const cached=localStorage.getItem(cacheKey);if(cached)setSd(JSON.parse(cached))}catch{}
    try{const r=await fetch(`/api/userdata?userId=${currentUser.id}`);const d=await r.json();setSd(d);try{localStorage.setItem(cacheKey,JSON.stringify(d))}catch{}}catch(e){console.log('Load error (offline?):',e)}
    setLoaded(true)})()},[currentUser]);

  useEffect(()=>{if(!currentUser)return;const url=currentUser.role==="admin"?"/api/docs":`/api/docs?userId=${currentUser.id}`;fetch(url).then(r=>r.json()).then(setDocs).catch(()=>{})},[currentUser]);

  const uploadDocs = async () => {
    if (!docFiles.length || !docStore || docUploading) return;
    setDocUploading(true); setDocError("");
    try {
      const fd = new FormData();
      docFiles.forEach(f => fd.append("files", f));
      fd.append("userName", currentUser?.name || "Unbekannt");
      fd.append("storeId", String(docStore.id || ""));
      fd.append("storeName", docStore.name || docStore.employer || "");
      fd.append("type", docType);
      fd.append("note", docNote);
      const r = await fetch("/api/docs", { method: "POST", body: fd });
      if (!r.ok) { setDocError("Server-Fehler: " + r.status); setDocUploading(false); return; }
      const j = await r.json();
      if (j.ok) {
        setDocs(d => [...d, { id: j.id, userId: currentUser.id, userName: currentUser.name, storeId: docStore.id, storeName: docStore.name || docStore.employer, type: docType, files: docFiles.map(f => f.name), note: docNote, createdAt: new Date().toISOString() }]);
        setDocFiles([]); setDocStore(null); setDocType("antrag"); setDocNote(""); setDocError(""); setPage("docs");
      } else {
        setDocError(j.error || "Upload fehlgeschlagen");
      }
    } catch (e) { setDocError("Verbindungsfehler: " + (e.message || "Kein Netz?")); }
    setDocUploading(false);
  };

  // ═══ SWIPE-BACK: vom linken Bildschirmrand nach rechts wischen → Zurück ═══
  useEffect(()=>{
    let sX=null,sY=null,sT=null,fired=false;
    const goBack=()=>{
      if(page==="detail"){setPage("list");setEditNote(false);setShowAV(false);return}
      if(page==="docs"&&docView){setDocView(null);return}
      if(page==="docUpload"){setPage("docs");setDocFiles([]);setDocStore(null);return}
      if(page==="docs"||page==="list"||page==="map"||page==="tour"||page==="stats"||page==="settings"){setPage("home");return}
    };
    const onStart=(e)=>{
      const t=e.touches&&e.touches[0];if(!t)return;
      // Nur Swipes, die ganz am linken Rand starten
      if(t.clientX>24){sX=null;return}
      sX=t.clientX;sY=t.clientY;sT=Date.now();fired=false;
    };
    const onMove=(e)=>{
      if(sX==null||fired)return;
      const t=e.touches&&e.touches[0];if(!t)return;
      const dx=t.clientX-sX, dy=Math.abs(t.clientY-sY), dt=Date.now()-sT;
      if(dx>70&&dy<55&&dt<600){fired=true;sX=null;goBack()}
    };
    const onEnd=()=>{sX=null};
    document.addEventListener("touchstart",onStart,{passive:true,capture:true});
    document.addEventListener("touchmove",onMove,{passive:true,capture:true});
    document.addEventListener("touchend",onEnd,{passive:true,capture:true});
    document.addEventListener("touchcancel",onEnd,{passive:true,capture:true});
    return()=>{
      document.removeEventListener("touchstart",onStart,{capture:true});
      document.removeEventListener("touchmove",onMove,{capture:true});
      document.removeEventListener("touchend",onEnd,{capture:true});
      document.removeEventListener("touchcancel",onEnd,{capture:true});
    };
  },[page]);

  // (Splash Auto-Rotation entfernt — neues Design braucht keine 3D-Karte)

  // ═══ Globaler Handler: Klick aufs Karten-Pop-up öffnet Detailmaske ═══
  openStoreRef.current=(sid)=>{
    const src=allStores.length>0?allStores:stores;
    const s=src.find(x=>String(x.id)===String(sid));
    if(!s)return;
    setSel(s);setPage("detail");setEditNote(false);setShowAV(false);
  };
  useEffect(()=>{
    window.__openStoreFromMap=(sid)=>{openStoreRef.current&&openStoreRef.current(sid)};
    return()=>{try{delete window.__openStoreFromMap}catch{}};
  },[]);

  useEffect(()=>{
    (async()=>{
      try{
        const cached=localStorage.getItem("allStores");
        const cacheTime=localStorage.getItem("allStoresTime");
        if(cached&&cacheTime&&(Date.now()-parseInt(cacheTime))<3600000){
          setAllStores(JSON.parse(cached));
          setAllStoresLoaded(true);
        }
        const res=await fetch('/api/stores/all');
        const data=await res.json();
        if(data.length>0){
          setAllStores(data);
          setAllStoresLoaded(true);
          try{const mini=data.map(s=>({id:s.id,employer:s.employer,name:s.name,lat:s.lat,lng:s.lng,city:s.city}));localStorage.setItem("allStores",JSON.stringify(mini));localStorage.setItem("allStoresTime",Date.now()+"")}catch(e){console.warn("Store-Cache zu gross:",e.message)}
        }
      }catch(e){console.log('AllStores load error:',e)}
    })();
  },[currentUser]);

  // Load stores from server based on location + radius
  const loadStoresRef=useRef(null);
  useEffect(()=>{
    if(loadStoresRef.current)clearTimeout(loadStoresRef.current);
    loadStoresRef.current=setTimeout(async()=>{
      const r=radius||50;
      const loc=planLoc||userLoc;
      setStoresLoading(true);
      try{
        const res=await fetch(`/api/stores?lat=${loc.lat}&lng=${loc.lng}&radius=${r}`);
        const data=await res.json();
        if(data.length>0)setStores(data);else setStores([]);
      }catch(e){console.log('Store load error:',e)}
      setStoresLoading(false);
    },500);
  },[userLoc.lat,userLoc.lng,radius,planLoc]);

  const save=useCallback(async d=>{
    if(!currentUser)return;
    const cacheKey=`userdata_${currentUser.id}`;
    try{localStorage.setItem(cacheKey,JSON.stringify(d))}catch{}
    try{
      const r=await fetch(`/api/userdata?userId=${currentUser.id}`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(d)});
      const j=await r.json();
      if(j.success){haptic();setSaveMsg("✅ Gespeichert")}else{setSaveMsg("⚠️ Fehler")}
    }catch{setSaveMsg("📴 Offline gespeichert");haptic()}
    if(stRef.current)clearTimeout(stRef.current);
    stRef.current=setTimeout(()=>setSaveMsg(""),2000);
  },[currentUser]);

  useEffect(()=>{
    if(currentUser)return;
    (async()=>{try{const r=await fetch('/api/users/login-list');setLoginUsers(await r.json())}catch{}})();
  },[currentUser]);
  const handleLogin=async()=>{
    if(!loginSelUser||!loginPin.trim()||loginLoading)return;
    setLoginLoading(true);setLoginError("");
    try{
      const r=await fetch('/api/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({userId:loginSelUser.id,pin:loginPin})});
      const j=await r.json();
      if(j.success){if(j.token)localStorage.setItem("authToken",j.token);setCurrentUser(j.user);localStorage.setItem("currentUser",JSON.stringify(j.user));setLoginPin("");setLoginSelUser(null)}
      else{setLoginError(j.error||"Falscher PIN");setLoginPin("")}
    }catch{setLoginError("Verbindungsfehler")}
    setLoginLoading(false);
  };
  const logout=()=>{setCurrentUser(null);localStorage.removeItem("currentUser");localStorage.removeItem("authToken");setSd({});setPage("home")};
  const saveProfile=async()=>{
    if(!currentUser)return;
    try{
      const payload={name:profileForm.name,region:profileForm.region,phone:profileForm.phone,email:profileForm.email};
      if(profileForm.newPin)payload.pin=profileForm.newPin;
      const r=await fetch(`/api/users/${currentUser.id}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
      const j=await r.json();
      if(j.success){const u={...currentUser,...payload};delete u.pin;setCurrentUser(u);localStorage.setItem("currentUser",JSON.stringify(u));setProfileEdit(false);
        if(profileForm.newPin)setSaveMsg("✅ PIN geändert")}
      else if(j.error){setSaveMsg("⚠️ "+j.error)}
    }catch{}
  };
  const createUser=async()=>{
    if(!newUser.name.trim()||!newUser.pin.trim())return;
    try{
      const r=await fetch('/api/users',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(newUser)});
      const j=await r.json();
      if(j.success){setShowAddUser(false);setNewUser({name:"",pin:"",role:"partner",region:"",phone:"",email:""});
        const r2=await fetch('/api/users');setAdminUsers(await r2.json())}
    }catch{}
  };
  const updateUserPin=async(userId)=>{
    if(!editUserPin.trim())return;
    try{
      const r=await fetch(`/api/users/${userId}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({pin:editUserPin})});
      const j=await r.json();
      if(j.success){setEditUserId(null);setEditUserPin("");setSaveMsg("✅ PIN geändert")}
      else if(j.error){setSaveMsg("⚠️ "+j.error)}
    }catch{}
  };
  const toggleUserActive=async(userId,currentlyActive)=>{
    try{
      const r=await fetch(`/api/users/${userId}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({active:!currentlyActive})});
      const j=await r.json();
      if(j.success){const r2=await fetch('/api/users');setAdminUsers(await r2.json())}
    }catch{}
  };
  useEffect(()=>{
    if(page!=="settings"||!currentUser||currentUser.role!=="admin")return;
    (async()=>{
      try{const r=await fetch('/api/users');setAdminUsers(await r.json())}catch{}
      try{const r=await fetch('/api/admin/team-stats');setTeamStats(await r.json())}catch{}
      try{const r=await fetch('/api/employer-suggestions');setEmpSuggestions(await r.json())}catch{}
    })();
  },[page,currentUser]);

  const upd=useCallback((id,u)=>{haptic();setSd(p=>{const n={...p,[id]:{...(p[id]||{}),...u,at:new Date().toISOString()}};save(n);return n})},[save]);

  const getCat=id=>sd[id]?.category||"besuchbar";
  const getData=id=>sd[id]||{};
  const getVisits=id=>sd[id]?.visits||[];
  const getClosures=id=>{const c=sd[id]?.closures;return Array.isArray(c)?c:[]};
  // Abschluss-Slot updaten — bei erstem Eintrag automatisch Status "geschrieben"
  // und Datum heute setzen, falls noch keins gesetzt
  const updateClosure=(sid,idx,changes)=>{
    const data=getData(sid);
    const cl=Array.isArray(data.closures)?[...data.closures]:[];
    while(cl.length<3)cl.push({});
    cl[idx]={...cl[idx],...changes};
    const slotFilled=(cl[idx].vorname&&cl[idx].vorname.trim())||(cl[idx].nachname&&cl[idx].nachname.trim());
    if(slotFilled&&!cl[idx].datum)cl[idx].datum=new Date().toISOString().slice(0,10);
    const anyFilled=cl.some(c=>c&&((c.nachname&&c.nachname.trim())||(c.vorname&&c.vorname.trim())));
    const u={closures:cl};
    if(anyFilled&&getCat(sid)!=="geschrieben"){u.category="geschrieben";u.lastVisit=new Date().toLocaleDateString("de-DE")}
    upd(sid,u);
  };

  const doAV=sid=>{
    if(!vS)return;
    const v={id:Date.now()+"",date:new Date().toLocaleDateString("de-DE"),time:new Date().toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}),status:vS,note:vN,objection:vO,contact:vC};
    const p=getData(sid);
    upd(sid,{visits:[...(p.visits||[]),v],category:vS,lastVisit:v.date,...(vC?{contact:vC}:{})});
    setShowAV(false);setVS("");setVN("");setVO("");setVC("");
  };

  const nav=s=>window.open(`https://www.google.com/maps/dir/?api=1&destination=${s.lat},${s.lng}&destination_place_id=${s.place_id}`,"_blank");

  const fl=stores.filter(s=>{
    const q=search.toLowerCase();
    const m=!search||s.name.toLowerCase().includes(q)||s.address.toLowerCase().includes(q)||s.employer.toLowerCase().includes(q)||s.branch.toLowerCase().includes(q);
    return m&&(fCat==="all"||getCat(s.id)===fCat);
  }).sort((a,b)=>distTo(a)-distTo(b));

  const st2={};["besuchbar","drin","geschrieben","abgelehnt"].forEach(k=>{st2[k]=stores.filter(s=>getCat(s.id)===k).length});st2.total=stores.length;

  // ═══ HEUTE + GAMIFICATION ═══
  const todayStr=new Date().toLocaleDateString("de-DE");
  let todayV=0,todayD=0,todayG=0,allV=0,allD=0,allG=0;
  const allDates=new Set();
  Object.values(sd).forEach(d=>{(d.visits||[]).forEach(v=>{
    allV++;if(v.date)allDates.add(v.date);
    if(v.status==="drin")allD++;if(v.status==="geschrieben")allG++;
    if(v.date===todayStr){todayV++;if(v.status==="drin")todayD++;if(v.status==="geschrieben")todayG++}
  });
  (d.closures||[]).forEach(c=>{
    if(!c)return;
    const filled=(c.nachname&&c.nachname.trim())||(c.vorname&&c.vorname.trim());
    if(!filled)return;
    let dateStr=c.datum||"";
    if(dateStr&&/^\d{4}-\d{2}-\d{2}$/.test(dateStr)){const [y,m,da]=dateStr.split("-");dateStr=`${da}.${m}.${y}`}
    if(dateStr)allDates.add(dateStr);
  });
  });
  const xp=allV*10+allD*15+allG*40;
  const LVLS=[{min:0,name:"Starter",icon:"🌱"},{min:100,name:"Bronze",icon:"🥉"},{min:500,name:"Silber",icon:"🥈"},{min:1500,name:"Gold",icon:"🥇"},{min:5000,name:"Diamant",icon:"💎"},{min:15000,name:"Legende",icon:"👑"}];
  const lvl=[...LVLS].reverse().find(l=>xp>=l.min)||LVLS[0];
  const nxtLvl=LVLS[LVLS.indexOf(lvl)+1];
  const lvlProg=nxtLvl?(xp-lvl.min)/(nxtLvl.min-lvl.min):1;
  let gStreak=0;
  for(let i=0;i<365;i++){const d=new Date(Date.now()-i*86400000);if(allDates.has(d.toLocaleDateString("de-DE")))gStreak++;else if(i===0)continue;else break}
  let earlyV=0,lateV=0,dayVisitMap={},uniqueEmps=new Set();
  Object.entries(sd).forEach(([sid,d])=>{
    const src=(allStores.length>0?allStores:stores).find(s=>String(s.id)===String(sid));
    if(src)uniqueEmps.add(src.employer);
    (d.visits||[]).forEach(v=>{
      if(v.time&&v.time<"09:00")earlyV++;
      if(v.time&&v.time>="18:00")lateV++;
      if(v.date){dayVisitMap[v.date]=(dayVisitMap[v.date]||0)+1}
    });
  });
  const maxDayV=Math.max(0,...Object.values(dayVisitMap));
  const BADGES=[
    {id:"fv",need:allV>=1,name:"Erster Besuch",icon:"⭐",desc:"1 Besuch"},
    {id:"v10",need:allV>=10,name:"10 Besuche",icon:"🔟",desc:"10 Besuche"},
    {id:"v50",need:allV>=50,name:"50 Besuche",icon:"🏅",desc:"50 Besuche"},
    {id:"v100",need:allV>=100,name:"Jahrhundert",icon:"💯",desc:"100 Besuche"},
    {id:"v500",need:allV>=500,name:"Marathonläufer",icon:"🏃",desc:"500 Besuche"},
    {id:"fc",need:allG>=1,name:"Erster Vertrag",icon:"📝",desc:"1 Vertrag"},
    {id:"c10",need:allG>=10,name:"Vertragsprofi",icon:"🏆",desc:"10 Verträge"},
    {id:"c50",need:allG>=50,name:"Deal-Maschine",icon:"🤑",desc:"50 Verträge"},
    {id:"s3",need:gStreak>=3,name:"3-Tage-Streak",icon:"🔥",desc:"3 Tage am Stück"},
    {id:"s7",need:gStreak>=7,name:"Woche durch!",icon:"⚡",desc:"7 Tage am Stück"},
    {id:"s30",need:gStreak>=30,name:"Monats-Streak",icon:"🌟",desc:"30 Tage am Stück"},
    {id:"q50",need:allD>0&&allG>0&&(allG/allD*100)>=50,name:"Closer",icon:"🎯",desc:"50%+ Abschlussquote"},
    {id:"h_early",need:earlyV>=5,name:"Frühaufsteher",icon:"🐓",desc:"5 Besuche vor 9 Uhr",secret:true},
    {id:"h_night",need:lateV>=3,name:"Nachtfalke",icon:"🦉",desc:"3 Besuche nach 18 Uhr",secret:true},
    {id:"h_marathon",need:maxDayV>=8,name:"Marathon",icon:"🏃‍♂️",desc:"8 Besuche an einem Tag",secret:true},
    {id:"h_allround",need:uniqueEmps.size>=10,name:"Allrounder",icon:"🌈",desc:"10 verschiedene Ketten besucht",secret:true},
    {id:"h_blitz",need:maxDayV>=3&&allG>=1,name:"Blitz-Closer",icon:"⚡",desc:"3+ Besuche & Vertrag am selben Tag",secret:true},
    {id:"h_1000xp",need:xp>=1000,name:"XP-Jäger",icon:"💎",desc:"1.000 XP erreicht",secret:true},
  ];

  // ═══ MAP (Leaflet + Clustering) ═══
  useEffect(()=>{
    if(page!=="map")return;
    let dead=false;
    (async()=>{
      const L=await loadLeaflet();if(dead)return;
      await loadMarkerCluster();if(dead)return;
      await loadLeafletRotate();if(dead)return;
      await new Promise(r=>setTimeout(r,200));
      if(dead||!mapRef.current)return;
      if(mapInst.current){try{mapInst.current.remove()}catch{}mapInst.current=null}

      const map=L.map(mapRef.current,{
        zoomControl:true, attributionControl:false,
        zoomSnap:0.25, zoomDelta:0.5,
        wheelDebounceTime:40, wheelPxPerZoomLevel:150,
        zoomAnimation:true, markerZoomAnimation:true, fadeAnimation:true,
        inertia:true, inertiaDeceleration:3400, inertiaMaxSpeed:2000,
        bounceAtZoomLimits:false, touchZoom:"center",
        // Karte mit zwei Fingern drehen (wie Google Maps)
        rotate:true, touchRotate:true, bearing:0, rotateControl:false,
      }).setView([51.1657,10.4515],6);
      L.tileLayer("https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png",{
        maxZoom:19, subdomains:"abcd",
        keepBuffer:6, updateWhenZooming:false, updateWhenIdle:true,
      }).addTo(map);
      mapInst.current=map;

      const mapCss=document.createElement("style");
      mapCss.id="leaflet-custom-css";
      const old=document.getElementById("leaflet-custom-css");if(old)old.remove();
      mapCss.textContent=`
        @keyframes gpspulse{0%{transform:scale(1);opacity:0.6}100%{transform:scale(3);opacity:0}}
        .pin-label{display:none;position:absolute;left:26px;top:0;white-space:nowrap;font-size:12px;font-weight:800;color:#0F172A;background:rgba(255,255,255,0.92);padding:1px 6px;border-radius:5px;box-shadow:0 1px 3px rgba(0,0,0,0.18);pointer-events:none;font-family:system-ui;line-height:1.4}
        .show-labels .pin-label{display:block}
        .mc-cluster{border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;color:white;font-family:system-ui;box-shadow:0 2px 8px rgba(0,0,0,0.3);border:2.5px solid white}
        .mc-small{background:#3B82F6;width:34px;height:34px;font-size:12px}
        .mc-medium{background:#7C3AED;width:40px;height:40px;font-size:13px}
        .mc-large{background:#F97316;width:48px;height:48px;font-size:14px}
      `;
      document.head.appendChild(mapCss);

      // Cluster-Gruppe
      const cluster=L.markerClusterGroup({
        maxClusterRadius:38,
        spiderfyOnMaxZoom:true,
        showCoverageOnHover:false,
        zoomToBoundsOnClick:true,
        disableClusteringAtZoom:13,
        iconCreateFunction:function(c){
          const n=c.getChildCount();
          let cls="mc-small";
          if(n>=50)cls="mc-large";
          else if(n>=10)cls="mc-medium";
          return L.divIcon({html:`<div class="mc-cluster ${cls}">${n}</div>`,className:"",iconSize:[48,48],iconAnchor:[24,24]});
        }
      });

      const mapData=allStores.length>0?allStores:stores;
      const branchMap={supermarkt:"🛒 Supermarkt",baumarkt:"🧰 Baumarkt"};
      const getCatM=id=>sdRef.current[id]?.category||"besuchbar";
      const getDataM=id=>sdRef.current[id]||{};
      let show=mf==="all"?mapData:mapData.filter(s=>getCatM(s.id)===mf);
      if(mapBranchF!=="all"){const w=branchMap[mapBranchF];if(w)show=show.filter(s=>s.branch===w)}
      if(mapStoreF){const sq=mapStoreF.toLowerCase();show=show.filter(s=>(s.name||"").toLowerCase().includes(sq)||(s.employer||"").toLowerCase().includes(sq))}
      show.forEach(store=>{
        const cat=getCatM(store.id),ci=CATS[cat]||CATS.besuchbar,d=getDataM(store.id);
        const icon=L.divIcon({
          html:`<div style="position:relative;"><div style="width:22px;height:22px;border-radius:50%;background:${ci.color};border:2.5px solid white;box-shadow:0 1px 6px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;font-size:11px;cursor:pointer;">${ci.icon}</div><div class="pin-label">${store.employer}</div></div>`,
          className:"",iconSize:[22,22],iconAnchor:[11,11],
        });
        const m=L.marker([store.lat,store.lng],{icon});
        const contact=d.contact?`<br/><span style="color:#3B82F6">👤 ${d.contact}</span>`:"";
        const vc=(d.visits||[]).length;
        const vi=vc>0?`<br/>📋 ${vc} Besuch${vc>1?"e":""}`:""
        m.bindPopup(`<div style="font-family:system-ui;min-width:210px;line-height:1.6;">
          <div onclick="window.__openStoreFromMap&&window.__openStoreFromMap('${store.id}')" style="cursor:pointer;padding:2px 0 4px;">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">
              ${logoHTML(store.employer,30)}
              <b style="font-size:15px;">${store.name}</b>
            </div>
            <span style="color:#666;font-size:12px;">${store.address}</span><br/>
            <span style="color:#60A5FA;font-weight:700;">📍 ${distStr(store)}</span> · <span style="color:#16a34a;font-weight:700;">VWL: ${store.vwl}</span><br/><span style="color:#888;font-size:12px;">${store.branch}</span>
            ${contact}${vi}
            <div style="margin-top:6px;font-size:11px;color:#3B82F6;font-weight:700;">→ Tippen für Details / Notizen</div>
          </div>
          <div style="display:flex;gap:6px;margin-top:8px;">
            <a href="https://www.google.com/maps/dir/?api=1&destination=${store.lat},${store.lng}&destination_place_id=${store.place_id}" target="_blank" onclick="event.stopPropagation()"
               style="flex:1;padding:10px 14px;background:#3B82F6;color:white;border-radius:10px;text-decoration:none;font-size:13px;font-weight:700;text-align:center;">
              🧭 Navigieren</a>
            <button onclick="event.stopPropagation();window.__openStoreFromMap&&window.__openStoreFromMap('${store.id}')"
               style="flex:1;padding:10px 14px;background:#0F172A;color:white;border:none;border-radius:10px;font-size:13px;font-weight:700;font-family:system-ui;cursor:pointer;">
              ✏️ Bearbeiten</button>
          </div>
        </div>`,{maxWidth:300});
        cluster.addLayer(m);
      });
      map.addLayer(cluster);

      // Zoom-Labels ein/ausblenden — Schwelle gesenkt, Labels schon ab dem
      // Zoom-Level sichtbar, ab dem die Cluster sich auflösen.
      const toggleLabels=()=>{
        const z=map.getZoom();
        const el=mapRef.current;
        if(!el)return;
        if(z>=12)el.classList.add("show-labels");
        else el.classList.remove("show-labels");
      };
      map.on("zoomend",toggleLabels);
      toggleLabels();

      if(userLoc.lat!==49.4925||userLoc.lng!==9.7744){
        map.setView([userLoc.lat,userLoc.lng],12);
      }

      // Tap on map to set planning location
      map.on('click',(e)=>{
        const la=e.latlng.lat,ln=e.latlng.lng;
        if(map._planM)map.removeLayer(map._planM);
        const pi=L.divIcon({html:`<div style="width:36px;height:36px;border-radius:50%;background:#7C3AED;border:3px solid white;box-shadow:0 2px 10px rgba(124,58,237,0.5);display:flex;align-items:center;justify-content:center;font-size:16px;">📍</div>`,className:"",iconSize:[36,36],iconAnchor:[18,18]});
        map._planM=L.marker([la,ln],{icon:pi,zIndexOffset:1800}).addTo(map);
        map._planM.bindPopup(`<div style="font-family:system-ui;text-align:center;padding:4px;"><b style="color:#7C3AED;">📍 Planungsort</b><br/><span style="font-size:11px;color:#666;">${la.toFixed(4)}°, ${ln.toFixed(4)}°</span></div>`);
        setPlanLoc({lat:la,lng:ln,name:`${la.toFixed(3)}°, ${ln.toFixed(3)}°`});
      });

      // Show planning marker if active
      if(planLoc){
        const pi=L.divIcon({html:`<div style="width:36px;height:36px;border-radius:50%;background:#7C3AED;border:3px solid white;box-shadow:0 2px 10px rgba(124,58,237,0.5);display:flex;align-items:center;justify-content:center;font-size:16px;">📍</div>`,className:"",iconSize:[36,36],iconAnchor:[18,18]});
        map._planM=L.marker([planLoc.lat,planLoc.lng],{icon:pi,zIndexOffset:1800}).addTo(map);
        map._planM.bindPopup(`<div style="font-family:system-ui;text-align:center;padding:4px;"><b style="color:#7C3AED;">📍 Planungsort</b><br/><span style="font-size:11px;color:#666;">${planLoc.name}</span></div>`);
      }

      // GPS - Blue dot with direction cone
      const defaultLat=49.4925, defaultLng=9.7744;
      const blueIcon=L.divIcon({
        html:`<div style="position:relative;width:80px;height:80px;">
          <div id="gps-cone" style="position:absolute;inset:0;transform:rotate(0deg);transition:transform 0.3s ease;pointer-events:none;">
            <svg width="80" height="80" viewBox="0 0 80 80"><path d="M40,40 L26,8 A18,18 0 0,1 54,8 Z" fill="rgba(66,133,244,0.25)"/></svg>
          </div>
          <div style="position:absolute;top:28px;left:28px;width:24px;height:24px;">
            <div style="position:absolute;inset:0;border-radius:50%;background:#4285F4;border:3.5px solid white;box-shadow:0 0 12px rgba(66,133,244,0.7),0 2px 6px rgba(0,0,0,0.3);z-index:2;"></div>
            <div style="position:absolute;inset:-10px;border-radius:50%;border:2.5px solid #4285F4;opacity:0.4;animation:gpspulse 2s ease-out infinite;z-index:1;"></div>
          </div>
        </div>`,
        className:"",iconSize:[80,80],iconAnchor:[40,40]
      });

      const initLat=userLoc.lat,initLng=userLoc.lng;
      let locM=L.marker([initLat,initLng],{icon:blueIcon,zIndexOffset:2000}).addTo(map);
      let locC=L.circle([initLat,initLng],{radius:150,color:"#4285F4",fillColor:"#4285F4",fillOpacity:0.08,weight:1.5,dashArray:"4"}).addTo(map);
      locM.bindPopup('<div style="font-family:system-ui;text-align:center;padding:4px;"><b style="color:#4285F4;">📍 Dein Standort</b></div>');

      const upLoc=(pos)=>{
        const la=pos.coords.latitude,ln=pos.coords.longitude,ac=pos.coords.accuracy;
        locM.setLatLng([la,ln]);
        locC.setLatLng([la,ln]).setRadius(Math.min(ac,300));
      };
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(upLoc,()=>{},{enableHighAccuracy:true,timeout:15000});
        map._gpsWatch=navigator.geolocation.watchPosition(upLoc,()=>{},{enableHighAccuracy:true,maximumAge:3000});
      }

      // Compass heading for direction cone
      const onHeading=(e)=>{
        let h=null;
        if(e.webkitCompassHeading!==undefined)h=e.webkitCompassHeading;
        else if(e.alpha!==null)h=360-e.alpha;
        if(h!==null){const c=document.getElementById("gps-cone");if(c)c.style.transform=`rotate(${h}deg)`}
      };
      // iOS 13+ permission
      if(typeof DeviceOrientationEvent!=="undefined"&&typeof DeviceOrientationEvent.requestPermission==="function"){
        DeviceOrientationEvent.requestPermission().then(r=>{if(r==="granted")window.addEventListener("deviceorientation",onHeading,true)}).catch(()=>{});
      }else{
        window.addEventListener("deviceorientationabsolute",onHeading,true);
        window.addEventListener("deviceorientation",onHeading,true);
      }
      map._headingHandler=onHeading;
    })();
    return()=>{dead=true;if(mapInst.current){if(mapInst.current._gpsWatch!=null)navigator.geolocation.clearWatch(mapInst.current._gpsWatch);if(mapInst.current._headingHandler){window.removeEventListener("deviceorientationabsolute",mapInst.current._headingHandler,true);window.removeEventListener("deviceorientation",mapInst.current._headingHandler,true)}try{mapInst.current.remove()}catch{}mapInst.current=null}};
  },[page,mf,allStores,planLoc,mapBranchF,mapStoreF]);

  const chip=(a,c)=>({
    padding:"7px 12px",background:a?c+"22":"#0F172A",
    border:a?`2px solid ${c}`:"2px solid #334155",
    borderRadius:20,color:a?c:"#94A3B8",
    fontSize:12,fontWeight:a?700:500,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap",
  });

  const gpsTimeStr=gpsTime?gpsTime.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"—";
  const GpsToggle=()=>{
    const dot=gpsStatus==="active"?"#22C55E":gpsStatus==="error"?"#EF4444":gpsStatus==="off"?"#64748B":"#F59E0B";
    const label=gpsStatus==="active"?"GPS aktiv":gpsStatus==="error"?("Kein GPS"+(gpsError?" · "+gpsError:"")):gpsStatus==="off"?"GPS aus":"Suche...";
    return(
      <div style={{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#94A3B8",flexWrap:"wrap"}}>
        {gpsStatus==="active"&&<span style={{color:"#64748B"}}>{gpsTimeStr}</span>}
        <div style={{width:8,height:8,borderRadius:"50%",background:dot,boxShadow:gpsStatus==="active"?`0 0 6px ${dot}`:"none"}}/>
        <span>{label}</span>
        <div onClick={()=>setGpsEnabled(!gpsEnabled)} style={{
          width:36,height:20,borderRadius:10,
          background:gpsEnabled?"#22C55E":"#475569",
          position:"relative",cursor:"pointer",transition:"background 0.2s",flexShrink:0
        }}>
          <div style={{
            width:16,height:16,borderRadius:"50%",background:"white",
            position:"absolute",top:2,left:gpsEnabled?18:2,
            transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.3)"
          }}/>
        </div>
      </div>
    );
  };

  const Sv=()=>saveMsg?<div style={{position:"fixed",top:12,left:"50%",transform:"translateX(-50%)",background:saveMsg.includes("✅")?"#166534":"#991B1B",color:"white",padding:"8px 18px",borderRadius:20,fontSize:13,fontWeight:600,zIndex:999,boxShadow:"0 4px 12px rgba(0,0,0,0.4)",fontFamily:"inherit"}}>{saveMsg}</div>:null;
  const BN=()=>(
    <div style={{position:"fixed",bottom:0,left:"50%",transform:"translateX(-50%)",width:"100%",maxWidth:480,background:"#1E293B",borderTop:"1px solid #334155",display:"flex",zIndex:30,paddingBottom:"env(safe-area-inset-bottom, 0px)"}}>
      {[{p:"home",i:"🏠",l:"Home"},{p:"list",i:"📋",l:"Liste"},{p:"map",i:"🗺",l:"Karte"},{p:"tour",i:"🧭",l:"Tour"},{p:"settings",i:"⚙️",l:"Mehr"}].map(n=>(
        <button key={n.p} onClick={()=>{haptic(5);setPage(n.p)}} style={{flex:1,padding:"10px 0",background:"transparent",border:"none",color:page===n.p?"#3B82F6":"#64748B",fontSize:11,fontWeight:600,cursor:"pointer",fontFamily:"inherit",display:"flex",flexDirection:"column",alignItems:"center",gap:2,position:"relative"}}>
          <span style={{fontSize:20}}>{n.i}</span>{n.l}
          {n.p==="tour"&&tour.length>0&&<span style={{position:"absolute",top:4,right:"calc(50% - 18px)",background:"#7C3AED",color:"white",fontSize:9,fontWeight:700,width:16,height:16,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center"}}>{tour.length}</span>}
        </button>
      ))}
    </div>
  );

  if(!loaded)return(<div style={{fontFamily:"system-ui",minHeight:"100dvh",background:"#0F172A",color:"#E2E8F0",maxWidth:480,margin:"0 auto",padding:20}}>
    <div style={{height:56,marginBottom:16}} className="skeleton"/>
    <div style={{height:120,marginBottom:12}} className="skeleton"/>
    <div style={{height:80,marginBottom:12}} className="skeleton"/>
    <div style={{height:80,marginBottom:12}} className="skeleton"/>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}><div style={{height:70}} className="skeleton"/><div style={{height:70}} className="skeleton"/></div>
  </div>);

  // ═══ DATENSCHUTZ-MODAL ═══
  if(!privacyAccepted)return(
    <div style={{fontFamily:"'DM Sans',system-ui,sans-serif",minHeight:"100dvh",background:"#0F172A",color:"#E2E8F0",maxWidth:480,margin:"0 auto",padding:"20px",overflowY:"auto"}}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
      <div style={{textAlign:"center",padding:"20px 0 10px"}}>
        <div style={{fontSize:48}}>🔒</div>
        <h1 style={{fontSize:22,fontWeight:700,margin:"12px 0 4px"}}>Datenschutzerklärung</h1>
        <div style={{fontSize:13,color:"#94A3B8"}}>Bitte lies und bestätige die folgenden Hinweise</div>
      </div>
      <div style={{background:"#1E293B",borderRadius:14,padding:20,marginBottom:16,fontSize:13,lineHeight:1.8,color:"#CBD5E1"}}>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8,marginTop:0}}>1. Verantwortlicher</h3>
        <p style={{margin:"0 0 16px"}}>Verantwortlich für die Datenverarbeitung im Sinne der DSGVO ist die Ki-Business Partnerschaft (nachfolgend „Betreiber"). Kontakt: dannyliebelt@outlook.de</p>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>2. Erhobene Daten</h3>
        <p style={{margin:"0 0 8px"}}>Im Rahmen der Nutzung dieser Anwendung werden folgende Daten erhoben und verarbeitet:</p>
        <ul style={{margin:"0 0 16px",paddingLeft:20}}>
          <li><b>Standortdaten (GPS):</b> Dein aktueller Standort wird zur Berechnung von Entfernungen zu Filialen und zur Routenplanung erfasst (Art. 6 Abs. 1 lit. a DSGVO).</li>
          <li><b>Besuchsdaten:</b> Besuchte Filialen, Datum, Uhrzeit, Ergebnis, Ansprechpartner und Notizen werden gespeichert.</li>
          <li><b>Aktivitätsdaten:</b> Anzahl der Besuche, Abschlussquoten, Streaks und weitere Leistungskennzahlen.</li>
          <li><b>Gerätedaten:</b> Kompass-Ausrichtung (DeviceOrientation) zur Anzeige der Blickrichtung auf der Karte.</li>
        </ul>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>3. Zweck der Datenverarbeitung</h3>
        <p style={{margin:"0 0 8px"}}>Die erhobenen Daten werden ausschließlich zu folgenden Zwecken verarbeitet:</p>
        <ul style={{margin:"0 0 16px",paddingLeft:20}}>
          <li><b>Vertriebssteuerung:</b> Planung und Dokumentation von Filialbesuchen.</li>
          <li><b>Auswertung & Analyse:</b> Erstellung von Leistungsübersichten und Statistiken zur Optimierung der Vertriebstätigkeit.</li>
          <li><b>Schulung & Unterstützung:</b> Anonymisierte Auswertungen können zur Verbesserung von Schulungsmaterialien und Vertriebsstrategien verwendet werden.</li>
          <li><b>Qualitätssicherung:</b> Nachvollziehbarkeit der Vertriebsaktivitäten gegenüber Kooperationspartnern.</li>
        </ul>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>4. Rechtsgrundlage</h3>
        <p style={{margin:"0 0 16px"}}>Die Verarbeitung erfolgt auf Grundlage deiner Einwilligung gem. Art. 6 Abs. 1 lit. a DSGVO sowie zur Durchführung des Vertriebspartnerschaftsvertrags gem. Art. 6 Abs. 1 lit. b DSGVO.</p>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>5. Ortungsdienste</h3>
        <p style={{margin:"0 0 16px"}}>Die App nutzt die GPS-Funktion deines Geräts. Die Standorterfassung erfolgt nur bei aktiver Nutzung der App und kann jederzeit in den App-Einstellungen deaktiviert werden. Standortdaten werden auf dem Server gespeichert und sind für den Betreiber einsehbar.</p>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>6. Speicherung & Sicherheit</h3>
        <p style={{margin:"0 0 16px"}}>Deine Daten werden auf einem gesicherten Server in der EU gespeichert. Die Übertragung erfolgt verschlüsselt (HTTPS). Es werden regelmäßige Backups erstellt. Eine Weitergabe an Dritte erfolgt nicht, es sei denn, dies ist zur Vertragserfüllung erforderlich oder gesetzlich vorgeschrieben.</p>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>7. Deine Rechte (Art. 15–21 DSGVO)</h3>
        <ul style={{margin:"0 0 16px",paddingLeft:20}}>
          <li><b>Auskunft</b> über die gespeicherten Daten (Art. 15 DSGVO)</li>
          <li><b>Berichtigung</b> unrichtiger Daten (Art. 16 DSGVO)</li>
          <li><b>Löschung</b> deiner Daten (Art. 17 DSGVO)</li>
          <li><b>Einschränkung</b> der Verarbeitung (Art. 18 DSGVO)</li>
          <li><b>Datenübertragbarkeit</b> (Art. 20 DSGVO)</li>
          <li><b>Widerspruch</b> gegen die Verarbeitung (Art. 21 DSGVO)</li>
          <li><b>Widerruf</b> deiner Einwilligung jederzeit mit Wirkung für die Zukunft</li>
        </ul>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>8. Beschwerderecht</h3>
        <p style={{margin:"0 0 16px"}}>Du hast das Recht, dich bei einer Datenschutz-Aufsichtsbehörde zu beschweren, wenn du der Ansicht bist, dass die Verarbeitung deiner Daten gegen die DSGVO verstößt.</p>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>9. Aufbewahrungsdauer</h3>
        <p style={{margin:"0 0 16px"}}>Deine Daten werden für die Dauer der Vertriebspartnerschaft gespeichert. Nach Beendigung werden sie innerhalb von 90 Tagen gelöscht, sofern keine gesetzlichen Aufbewahrungspflichten entgegenstehen.</p>

        <h3 style={{color:"#E2E8F0",fontSize:15,marginBottom:8}}>10. Änderungen</h3>
        <p style={{margin:"0 0 0"}}>Der Betreiber behält sich vor, diese Datenschutzerklärung bei Bedarf anzupassen. Über wesentliche Änderungen wirst du informiert.</p>
      </div>

      <div style={{background:"#1E293B",borderRadius:14,padding:16,marginBottom:16,border:"1px solid #334155"}}>
        <div style={{fontSize:13,color:"#CBD5E1",lineHeight:1.6}}>
          Mit der Bestätigung erklärst du dich einverstanden, dass:
        </div>
        <ul style={{fontSize:13,color:"#CBD5E1",lineHeight:1.8,margin:"8px 0 0",paddingLeft:20}}>
          <li>dein <b>Standort</b> zur Entfernungsberechnung und Routenplanung erfasst wird</li>
          <li>deine <b>Besuchs- und Aktivitätsdaten</b> gespeichert und ausgewertet werden</li>
          <li>Daten zu <b>Schulungs- und Unterstützungszwecken</b> verwendet werden dürfen</li>
          <li>du die obige Datenschutzerklärung gelesen und verstanden hast</li>
        </ul>
      </div>

      <button onClick={()=>{localStorage.setItem("privacyAccepted",new Date().toISOString());setPrivacyAccepted(true)}} style={{width:"100%",padding:"16px",background:"#22C55E",border:"none",borderRadius:14,color:"white",fontSize:16,fontWeight:700,cursor:"pointer",fontFamily:"inherit",boxShadow:"0 4px 12px rgba(34,197,94,0.3)",marginBottom:12}}>
        Ich stimme zu und akzeptiere
      </button>
      <div style={{textAlign:"center",fontSize:11,color:"#64748B",padding:"0 20px"}}>
        Stand: April 2026 · Ki-Business Partnerschaft
      </div>
    </div>
  );

  // ═══ FÖRDERBERATUNG SPLASH-SCREEN — Apple-Style Reveal ═══
  if(privacyAccepted && !currentUser && !splashShownToday){
    const dismissSplash=()=>{
      const t=new Date().toLocaleDateString("de-DE");
      localStorage.setItem("splashShownDate",t);
      setSplashShownToday(true);
    };
    return(
      <div onClick={dismissSplash} style={{position:"fixed",inset:0,background:"#050B1C",overflow:"hidden",fontFamily:"'DM Sans',system-ui,sans-serif",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",zIndex:9999,cursor:"pointer",WebkitTapHighlightColor:"transparent",userSelect:"none",WebkitUserSelect:"none",touchAction:"manipulation"}}>
        <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
        <style>{`
          @keyframes splSkylineIn{from{opacity:0}to{opacity:1}}
          @keyframes splLogoReveal{from{opacity:0;transform:scale(0.92)}to{opacity:1;transform:scale(1)}}
          @keyframes splTextReveal{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
          @keyframes splHintIn{from{opacity:0}to{opacity:1}}
          @keyframes splHintPulse{0%,100%{opacity:0.4}50%{opacity:0.8}}
          @keyframes splGlowIn{from{opacity:0}to{opacity:1}}
        `}</style>

        {/* Skyline-Hintergrund */}
        <div style={{position:"absolute",inset:0,opacity:0,animation:"splSkylineIn 2.5s ease-out 0.2s forwards"}}>
          <div style={{position:"absolute",inset:0,backgroundImage:"url('/skyline-ref.jpg')",backgroundSize:"contain",backgroundPosition:"center center",backgroundRepeat:"no-repeat"}}/>
          <div style={{position:"absolute",inset:0,background:"rgba(5,11,28,0.72)"}}/>
        </div>

        {/* Dezenter Glow */}
        <div style={{position:"absolute",width:"70vw",height:"70vw",maxWidth:300,maxHeight:300,borderRadius:"50%",background:"radial-gradient(circle,rgba(232,184,75,0.08) 0%,transparent 70%)",top:"50%",left:"50%",transform:"translate(-50%,-55%)",opacity:0,animation:"splGlowIn 2s ease 1.5s forwards"}}/>

        {/* Content */}
        <div style={{position:"relative",zIndex:2,display:"flex",flexDirection:"column",alignItems:"center",gap:0,padding:"0 24px",marginTop:"-6vh"}}>
          <img src="/foerderberatung-logo.png" alt="Logo" style={{width:"min(120px, 30vw)",height:"auto",opacity:0,transform:"scale(0.92)",animation:"splLogoReveal 1.2s cubic-bezier(0.16,1,0.3,1) 0.3s forwards"}}/>

          <div style={{marginTop:"clamp(16px, 4vh, 28px)",textAlign:"center",opacity:0,transform:"translateY(6px)",animation:"splTextReveal 1s cubic-bezier(0.16,1,0.3,1) 1.2s forwards"}}>
            <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"clamp(14px, 4.5vw, 18px)",fontWeight:600,color:"#E8B84B",letterSpacing:"clamp(3px, 1.5vw, 6px)",textTransform:"uppercase",marginBottom:2}}>Die</div>
            <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"clamp(22px, 7vw, 28px)",fontWeight:700,color:"#E2E8F0",letterSpacing:"clamp(1px, 0.5vw, 2px)",textTransform:"uppercase"}}>Förderberatung</div>
          </div>

          <div style={{width:"clamp(30px, 10vw, 40px)",height:1,background:"linear-gradient(90deg,transparent,#E8B84B,transparent)",marginTop:"clamp(14px, 3vh, 20px)",opacity:0,animation:"splTextReveal 1s cubic-bezier(0.16,1,0.3,1) 1.8s forwards"}}/>

          <div style={{marginTop:"clamp(10px, 2vh, 16px)",fontFamily:"'DM Sans',sans-serif",fontSize:"clamp(10px, 2.8vw, 12px)",fontWeight:500,color:"#E8B84B",letterSpacing:"clamp(2px, 1vw, 4px)",textTransform:"uppercase",opacity:0,animation:"splTextReveal 1s cubic-bezier(0.16,1,0.3,1) 2.0s forwards"}}>Dein Anspruch, unser Job!</div>
        </div>

        {/* Hinweis */}
        <div style={{position:"absolute",bottom:"calc(24px + env(safe-area-inset-bottom, 0px))",left:0,right:0,textAlign:"center",fontSize:"clamp(11px, 3vw, 13px)",color:"#475569",letterSpacing:1,opacity:0,animation:"splHintIn 1s ease 3.5s forwards"}}>
          <span style={{animation:"splHintPulse 3s ease-in-out infinite"}}>Tippen zum Fortfahren</span>
        </div>
      </div>
    );
  }

  // ═══ LOGIN-SCREEN ═══
  if(!currentUser)return(
    <div style={{fontFamily:"'DM Sans',system-ui,sans-serif",minHeight:"100dvh",background:"#0F172A",color:"#E2E8F0",maxWidth:480,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:20}}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
      <div style={{fontSize:48,marginBottom:8}}>🔥</div>
      <h1 style={{fontSize:24,fontWeight:700,margin:"0 0 4px"}}>Vertrieb CRM</h1>
      <div style={{fontSize:13,color:"#94A3B8",marginBottom:24}}>{loginSelUser?"PIN":"Wer bist du?"}</div>

      {!loginSelUser?(
        <div style={{width:"100%",maxWidth:320}}>
          {loginUsers.filter(u=>u.active!==false).map(u=>(
            <div key={u.id} onClick={()=>{setLoginSelUser(u);setLoginPin("");setLoginError("")}} style={{display:"flex",alignItems:"center",gap:12,background:"#1E293B",borderRadius:14,padding:"14px 16px",marginBottom:8,cursor:"pointer",border:"2px solid #334155",transition:"border 0.2s"}}>
              <div style={{width:44,height:44,borderRadius:"50%",background:u.role==="admin"?"#F59E0B22":"#3B82F622",border:u.role==="admin"?"2px solid #F59E0B":"2px solid #3B82F6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:u.role==="admin"?"#F59E0B":"#3B82F6",flexShrink:0}}>{(u.name||"?")[0]}</div>
              <div style={{flex:1}}>
                <div style={{fontWeight:700,fontSize:15}}>{u.name}</div>
                {u.region&&<div style={{fontSize:12,color:"#64748B"}}>{u.region}</div>}
              </div>
              <div style={{fontSize:18,color:"#334155"}}>→</div>
            </div>
          ))}
          {loginUsers.length===0&&<div style={{fontSize:13,color:"#64748B",textAlign:"center",padding:20}}>Lade Nutzer...</div>}
        </div>
      ):(
        <div style={{width:"100%",maxWidth:280}}>
          <div onClick={()=>{setLoginSelUser(null);setLoginPin("");setLoginError("")}} style={{display:"flex",alignItems:"center",gap:10,background:"#1E293B",borderRadius:12,padding:"10px 14px",marginBottom:16,cursor:"pointer",border:"1px solid #334155"}}>
            <div style={{fontSize:14}}>←</div>
            <div style={{width:32,height:32,borderRadius:"50%",background:loginSelUser.role==="admin"?"#F59E0B22":"#3B82F622",border:loginSelUser.role==="admin"?"2px solid #F59E0B":"2px solid #3B82F6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:700,color:loginSelUser.role==="admin"?"#F59E0B":"#3B82F6"}}>{(loginSelUser.name||"?")[0]}</div>
            <div style={{fontWeight:600,fontSize:14}}>{loginSelUser.name}</div>
          </div>
          <input value={loginPin} onChange={e=>setLoginPin(e.target.value.replace(/[^0-9]/g,""))} onKeyDown={e=>{if(e.key==="Enter")handleLogin()}}
            type="password" inputMode="numeric" pattern="[0-9]*" maxLength={6} placeholder="PIN" autoFocus
            style={{width:"100%",padding:"16px",background:"#1E293B",border:"2px solid #334155",borderRadius:14,color:"#E2E8F0",fontSize:24,fontWeight:700,textAlign:"center",letterSpacing:12,fontFamily:"inherit",boxSizing:"border-box"}}/>
          {loginError&&<div style={{background:"#991B1B",borderRadius:10,padding:"10px 14px",marginTop:12,fontSize:13,color:"white",textAlign:"center"}}>{loginError}</div>}
          <button onClick={handleLogin} disabled={!loginPin.trim()||loginLoading} style={{width:"100%",marginTop:16,padding:"16px",background:loginPin.trim()?"#3B82F6":"#334155",border:"none",borderRadius:14,color:"white",fontSize:16,fontWeight:700,cursor:loginPin.trim()?"pointer":"default",fontFamily:"inherit",opacity:loginPin.trim()?1:0.5}}>
            {loginLoading?"Anmelden...":"Anmelden"}
          </button>
        </div>
      )}
    </div>
  );

  const Z={fontFamily:"'DM Sans',system-ui,sans-serif",minHeight:"100dvh",background:"#0F172A",color:"#E2E8F0",maxWidth:480,margin:"0 auto",paddingBottom:70,animation:"pageIn 0.18s ease-out both"};
  const HH={padding:"14px 20px",display:"flex",alignItems:"center",gap:12,borderBottom:"1px solid #1E293B",background:"#0F172A",position:"sticky",top:0,zIndex:20};
  const BB={background:"#1E293B",border:"none",borderRadius:10,width:38,height:38,display:"flex",alignItems:"center",justifyContent:"center",color:"#E2E8F0",fontSize:18,cursor:"pointer"};
  const CC={background:"#1E293B",borderRadius:14,padding:16,marginBottom:10};
  const II={width:"100%",padding:"10px 12px",background:"#0F172A",border:"1px solid #334155",borderRadius:8,color:"#E2E8F0",fontSize:14,fontFamily:"inherit",boxSizing:"border-box"};

  // ══════ PAGE CONTENT (Nav-Bar bleibt immer sichtbar) ══════
  let pageContent=null;

  // ══════ HOME ══════
  if(page==="home"){
    const nearStores=fl.slice(0,3);
    const nextBadge=BADGES.find(b=>!b.need);
    let badgeProg=0,badgeTarget=1;
    if(nextBadge){
      if(nextBadge.id==="fv"){badgeProg=allV;badgeTarget=1}
      else if(nextBadge.id==="v10"){badgeProg=allV;badgeTarget=10}
      else if(nextBadge.id==="v50"){badgeProg=allV;badgeTarget=50}
      else if(nextBadge.id==="v100"){badgeProg=allV;badgeTarget=100}
      else if(nextBadge.id==="v500"){badgeProg=allV;badgeTarget=500}
      else if(nextBadge.id==="fc"){badgeProg=allG;badgeTarget=1}
      else if(nextBadge.id==="c10"){badgeProg=allG;badgeTarget=10}
      else if(nextBadge.id==="c50"){badgeProg=allG;badgeTarget=50}
      else if(nextBadge.id==="s3"){badgeProg=gStreak;badgeTarget=3}
      else if(nextBadge.id==="s7"){badgeProg=gStreak;badgeTarget=7}
      else if(nextBadge.id==="s30"){badgeProg=gStreak;badgeTarget=30}
      else if(nextBadge.id==="q50"){badgeProg=allD>0&&allG>0?Math.round(allG/allD*100):0;badgeTarget=50}
    }
    const badgePct=nextBadge?Math.min(badgeProg/badgeTarget,1):1;
    const fname=currentUser?currentUser.name.split(" ")[0]:"";
    const h=new Date().getHours();
    const greetPool=[];
    if(h<10)greetPool.push(`Guten Morgen ${fname}! ☀️`,`Moin ${fname}! ☕`,`Rise & Grind, ${fname}! 💪`,`Na ${fname}, ausgeschlafen? 😴`,`Frühaufsteher ${fname}! 🐓`,`Erstmal Kaffee, ${fname}? ☕`);
    else if(h<13)greetPool.push(`Hey ${fname}! 👋`,`Los geht's, ${fname}! 🚀`,`Vollgas ${fname}! 💨`,`${fname} ist am Start! 🔥`,`Auf die Plätze, ${fname}! 🏁`,`Rein da, ${fname}! 🤝`);
    else if(h<17)greetPool.push(`Weiter so, ${fname}! 💪`,`Halbzeit ${fname}! ⚡`,`Nicht nachlassen, ${fname}! 🎯`,`${fname} macht Meter! 🏃`,`Stark unterwegs, ${fname}! 🔥`,`${fname} räumt ab! 💸`);
    else greetPool.push(`Feierabend ${fname}? 🌙`,`Was für ein Tag, ${fname}! 🙌`,`${fname} hat abgeliefert! 🏆`,`Gut gemacht, ${fname}! ⭐`,`Entspannter Abend, ${fname}! 🍕`,`Morgen geht's weiter, ${fname}! 😎`);
    if(gStreak>=7)greetPool.push(`${gStreak} Tage Streak — Maschine! 🤖`,`${fname} kennt kein Wochenende! 🔥`);
    else if(gStreak>=3)greetPool.push(`${gStreak}-Tage-Streak, nice! 🔥`);
    if(todayG>0)greetPool.push(`Schon ${todayG} Vertrag${todayG>1?"e":""} heute — Respekt! 💰`);
    if(todayV>=5)greetPool.push(`${todayV} Besuche heute — du bist on fire! 🔥`);
    if(allG>=50)greetPool.push(`${allG} Verträge gesamt — Legend! 👑`);
    const dayIdx=new Date().getDate()+new Date().getMonth()*31;
    const greeting=greetPool[dayIdx%greetPool.length];
    pageContent=(
      <div style={Z}>
        <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
        <div style={{padding:"20px 20px 0",background:"linear-gradient(180deg,#1E293B 0%,#0F172A 100%)"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
            <div>
              <div style={{fontSize:22,fontWeight:700}}>{greeting}</div>
              <div style={{fontSize:13,color:"#94A3B8",marginTop:2}}>{new Date().toLocaleDateString("de-DE",{weekday:"long",day:"numeric",month:"long"})}</div>
            </div>
            <div style={{display:"flex",alignItems:"center",gap:6}}>
              <div style={{background:"#0F172A",borderRadius:8,padding:"4px 10px",display:"flex",alignItems:"center",gap:4,border:"1px solid #334155"}}>
                <span style={{fontSize:14}}>{lvl.icon}</span>
                <span style={{fontSize:11,fontWeight:700,color:"#C4B5FD"}}>{lvl.name}</span>
              </div>
              {gStreak>0&&<div style={{background:"#F9731622",borderRadius:8,padding:"4px 10px",border:"1px solid #F97316",display:"flex",alignItems:"center",gap:4}}>
                <span style={{fontSize:11,fontWeight:700,color:"#F97316"}}>{gStreak}🔥</span>
              </div>}
            </div>
          </div>
          <div style={{marginTop:12,marginBottom:16}}>
            <div style={{display:"flex",justifyContent:"space-between",fontSize:11,color:"#64748B",marginBottom:4}}>
              <span>{xp} XP</span>
              {nxtLvl&&<span>{nxtLvl.icon} {nxtLvl.name} · noch {nxtLvl.min-xp} XP</span>}
            </div>
            <div style={{height:6,background:"#334155",borderRadius:3,overflow:"hidden"}}>
              <div style={{height:"100%",width:`${lvlProg*100}%`,background:"linear-gradient(90deg,#7C3AED,#A78BFA)",borderRadius:3,transition:"width 0.5s"}}/>
            </div>
          </div>
        </div>

        <div style={{padding:"12px 20px 100px"}}>
          <div onClick={()=>setPage("stats")} style={{...CC,border:"1px solid #334155",cursor:"pointer"}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10}}>
              <div style={{fontSize:14,fontWeight:700}}>📊 Heute, {new Date().toLocaleDateString("de-DE",{day:"numeric",month:"short"})}</div>
              <div style={{fontSize:11,color:"#3B82F6",fontWeight:600}}>Details →</div>
            </div>
            {todayV===0?(
              <div style={{fontSize:13,color:"#64748B"}}>Noch keine Besuche — leg los! 💪</div>
            ):(
              <div style={{display:"flex",gap:12}}>
                <div style={{textAlign:"center",flex:1,background:"#0F172A",borderRadius:10,padding:"10px 4px"}}>
                  <div style={{fontSize:28,fontWeight:700,color:"#60A5FA"}}>{todayV}</div>
                  <div style={{fontSize:10,color:"#94A3B8"}}>Besuche</div>
                </div>
                <div style={{textAlign:"center",flex:1,background:"#0F172A",borderRadius:10,padding:"10px 4px"}}>
                  <div style={{fontSize:28,fontWeight:700,color:"#3B82F6"}}>{todayD}</div>
                  <div style={{fontSize:10,color:"#94A3B8"}}>Rein</div>
                </div>
                <div style={{textAlign:"center",flex:1,background:"#0F172A",borderRadius:10,padding:"10px 4px"}}>
                  <div style={{fontSize:28,fontWeight:700,color:"#22C55E"}}>{todayG}</div>
                  <div style={{fontSize:10,color:"#94A3B8"}}>Geschrieben</div>
                </div>
              </div>
            )}
          </div>

          <div onClick={()=>setPage("list")} style={{...CC,border:"1px solid #334155",cursor:"pointer"}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10}}>
              <div style={{fontSize:14,fontWeight:700}}>📍 In der Nähe</div>
              <div style={{fontSize:11,color:"#3B82F6",fontWeight:600}}>Alle {fl.length} →</div>
            </div>
            {nearStores.length>0?nearStores.map(store=>{
              const ci=CATS[getCat(store.id)]||CATS.besuchbar;
              return(
                <div key={store.id} style={{display:"flex",alignItems:"center",gap:10,padding:"8px 0",borderBottom:"1px solid #0F172A"}}>
                  <Logo employer={store.employer} size={34}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontWeight:600,fontSize:13}}>{store.name}</div>
                    <div style={{fontSize:11,color:"#94A3B8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{store.address}</div>
                  </div>
                  <div style={{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0}}>
                    <div style={{fontSize:12,color:"#60A5FA",fontWeight:700}}>{distStr(store)}</div>
                    <div style={{fontSize:10,color:"#94A3B8"}}>{ci.icon} {ci.label}</div>
                  </div>
                </div>
              );
            }):<div style={{fontSize:13,color:"#64748B"}}>Lade Filialen...</div>}
          </div>

          <div onClick={()=>setPage("tour")} style={{...CC,border:`1px solid ${tour.length>0?"#7C3AED":"#334155"}`,cursor:"pointer"}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:tour.length>0?10:0}}>
              <div style={{fontSize:14,fontWeight:700}}>🧭 Deine Tour</div>
              {tour.length>0&&<div style={{background:"#7C3AED",color:"white",fontSize:11,fontWeight:700,padding:"2px 8px",borderRadius:10}}>{tour.length} Stops</div>}
            </div>
            {tour.length===0?(
              <div style={{fontSize:13,color:"#64748B",marginTop:6}}>Noch keine Stops geplant — füge Läden aus der Liste hinzu</div>
            ):(
              <div style={{display:"flex",gap:6,overflowX:"auto",paddingBottom:2}}>
                {tour.slice(0,4).map(s=>(
                  <div key={s.id} style={{display:"flex",alignItems:"center",gap:6,background:"#0F172A",borderRadius:8,padding:"6px 10px",flexShrink:0}}>
                    <Logo employer={s.employer} size={24}/>
                    <div style={{fontSize:11,fontWeight:600,whiteSpace:"nowrap"}}>{s.employer}</div>
                  </div>
                ))}
                {tour.length>4&&<div style={{display:"flex",alignItems:"center",padding:"6px 10px",fontSize:11,color:"#7C3AED",fontWeight:600}}>+{tour.length-4}</div>}
              </div>
            )}
          </div>

          <div onClick={()=>setPage("docs")} style={{...CC,border:"1px solid #334155",cursor:"pointer"}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div style={{fontSize:14,fontWeight:700}}>📄 Dokumente</div>
              <div style={{fontSize:11,color:"#3B82F6",fontWeight:600}}>{docs.length} gesamt →</div>
            </div>
            <div style={{fontSize:12,color:"#94A3B8",marginTop:6}}>{docs.filter(d=>d.createdAt?.startsWith(new Date().toISOString().split("T")[0])).length} heute hochgeladen</div>
          </div>

          {nextBadge&&<div onClick={()=>setPage("stats")} style={{...CC,border:"1px solid #334155",cursor:"pointer"}}>
            <div style={{fontSize:14,fontWeight:700,marginBottom:10}}>🏆 Nächste Auszeichnung</div>
            <div style={{display:"flex",alignItems:"center",gap:12}}>
              <div style={{fontSize:36}}>{nextBadge.icon}</div>
              <div style={{flex:1}}>
                <div style={{fontWeight:700,fontSize:14}}>{nextBadge.name}</div>
                <div style={{fontSize:12,color:"#94A3B8"}}>{nextBadge.desc}</div>
                <div style={{height:6,background:"#334155",borderRadius:3,overflow:"hidden",marginTop:6}}>
                  <div style={{height:"100%",width:`${badgePct*100}%`,background:"linear-gradient(90deg,#F97316,#FB923C)",borderRadius:3,transition:"width 0.5s"}}/>
                </div>
                <div style={{fontSize:10,color:"#64748B",marginTop:3}}>{badgeProg} / {badgeTarget}</div>
              </div>
            </div>
          </div>}

          <div onClick={()=>setPage("stats")} style={{...CC,border:"1px solid #334155",cursor:"pointer",textAlign:"center",padding:16,marginTop:4,marginBottom:0}}>
            <div style={{fontSize:24,marginBottom:4}}>📊</div>
            <div style={{fontSize:13,fontWeight:600}}>Statistiken</div>
            <div style={{fontSize:10,color:"#64748B",marginTop:2}}>{allV} Besuche total</div>
          </div>
        </div>
      </div>
    );
  }

  // ══════ DOKUMENTE ══════
  if(page==="docs"||page==="docUpload"){
    const docTypes=[{id:"antrag",icon:"📝",label:"Antrag"},{id:"gehalt",icon:"💰",label:"Gehaltsnachweis"},{id:"vollmacht",icon:"📋",label:"Vollmacht"},{id:"sonstiges",icon:"📎",label:"Sonstiges"}];
    const todayDocs=docs.filter(d=>d.createdAt?.startsWith(new Date().toISOString().split("T")[0]));
    const olderDocs=docs.filter(d=>!d.createdAt?.startsWith(new Date().toISOString().split("T")[0]));

    if(page==="docUpload"){
      const recentStores=fl.slice(0,20);
      const filteredStores=search?fl.filter(s=>s.name.toLowerCase().includes(search.toLowerCase())||s.employer.toLowerCase().includes(search.toLowerCase())).slice(0,10):recentStores;
      pageContent=(
        <div style={Z}>
          <div style={HH}>
            <button onClick={()=>{setPage("docs");setDocFiles([]);setDocStore(null);setDocType("antrag");setDocNote("")}} style={BB}>←</button>
            <div style={{flex:1}}><div style={{fontWeight:700,fontSize:17}}>Dokument hochladen</div></div>
          </div>
          <div style={{padding:"0 20px 100px"}}>
            {!docStore?(
              <div style={CC}>
                <div style={{fontSize:13,color:"#94A3B8",marginBottom:10}}>Filiale auswählen</div>
                <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Filiale suchen..." style={{width:"100%",padding:"10px 12px",background:"#0F172A",border:"1px solid #334155",borderRadius:8,color:"#E2E8F0",fontSize:13,fontFamily:"inherit",marginBottom:10,boxSizing:"border-box"}}/>
                <div style={{maxHeight:300,overflowY:"auto"}}>
                  {filteredStores.map(s=>(
                    <div key={s.id} onClick={()=>{setDocStore(s);setSearch("")}} style={{display:"flex",alignItems:"center",gap:10,padding:"10px 0",borderBottom:"1px solid #1E293B",cursor:"pointer"}}>
                      <Logo employer={s.employer} size={30}/>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontWeight:600,fontSize:13}}>{s.name}</div>
                        <div style={{fontSize:11,color:"#94A3B8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{s.address}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ):(
              <>
                <div style={{...CC,display:"flex",alignItems:"center",gap:10}}>
                  <Logo employer={docStore.employer} size={34}/>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:600,fontSize:13}}>{docStore.name}</div>
                    <div style={{fontSize:11,color:"#94A3B8"}}>{docStore.employer}</div>
                  </div>
                  <button onClick={()=>setDocStore(null)} style={{background:"#334155",border:"none",borderRadius:8,padding:"6px 10px",color:"#94A3B8",fontSize:11,cursor:"pointer"}}>Ändern</button>
                </div>

                <div style={CC}>
                  <div style={{fontSize:13,color:"#94A3B8",marginBottom:8}}>Dokumenttyp</div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                    {docTypes.map(t=>(
                      <button key={t.id} onClick={()=>setDocType(t.id)} style={{padding:"10px",background:docType===t.id?"#1E3A5F":"#0F172A",border:`1px solid ${docType===t.id?"#3B82F6":"#334155"}`,borderRadius:8,color:"#E2E8F0",fontSize:12,fontWeight:600,cursor:"pointer",textAlign:"center"}}>
                        <span style={{fontSize:18,display:"block",marginBottom:2}}>{t.icon}</span>{t.label}
                      </button>
                    ))}
                  </div>
                </div>

                <div style={CC}>
                  <div style={{fontSize:13,color:"#94A3B8",marginBottom:8}}>Fotos ({docFiles.length}/10)</div>
                  <label style={{display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"20px",background:"#0F172A",border:"2px dashed #334155",borderRadius:10,cursor:"pointer",fontSize:13,color:"#64748B"}}>
                    <span style={{fontSize:24}}>📷</span> Foto aufnehmen oder auswählen
                    <input type="file" accept="image/*,application/pdf" capture="environment" multiple onChange={e=>{if(e.target.files)setDocFiles(f=>[...f,...Array.from(e.target.files)].slice(0,10))}} style={{display:"none"}}/>
                  </label>
                  {docFiles.length>0&&(
                    <div style={{display:"flex",gap:8,marginTop:10,overflowX:"auto",paddingBottom:4}}>
                      {docFiles.map((f,i)=>(
                        <div key={i} style={{position:"relative",flexShrink:0}}>
                          <img src={URL.createObjectURL(f)} style={{width:60,height:60,objectFit:"cover",borderRadius:8,border:"1px solid #334155"}}/>
                          <button onClick={()=>setDocFiles(x=>x.filter((_,j)=>j!==i))} style={{position:"absolute",top:-6,right:-6,width:20,height:20,borderRadius:"50%",background:"#EF4444",border:"none",color:"white",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>✕</button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                <div style={CC}>
                  <div style={{fontSize:13,color:"#94A3B8",marginBottom:8}}>Notiz (optional)</div>
                  <textarea value={docNote} onChange={e=>setDocNote(e.target.value)} placeholder="z.B. Antrag Seite 1+2, fehlt noch Unterschrift..." rows={2} style={{width:"100%",padding:"10px 12px",background:"#0F172A",border:"1px solid #334155",borderRadius:8,color:"#E2E8F0",fontSize:13,fontFamily:"inherit",resize:"none",boxSizing:"border-box"}}/>
                </div>

                {docError&&<div style={{background:"#7F1D1D",border:"1px solid #EF4444",borderRadius:8,padding:"8px 12px",marginTop:8,fontSize:12,color:"#FCA5A5"}}>{docError}</div>}

                <button onClick={uploadDocs} disabled={!docFiles.length||docUploading} style={{width:"100%",padding:"14px",background:docFiles.length&&!docUploading?"linear-gradient(135deg, #3B82F6, #7C3AED)":"#334155",border:"none",borderRadius:12,color:"white",fontSize:15,fontWeight:700,cursor:docFiles.length&&!docUploading?"pointer":"default",fontFamily:"inherit",marginTop:8}}>
                  {docUploading?"Wird hochgeladen...":"📤 Hochladen"}
                </button>
              </>
            )}
          </div>
        </div>
      );
    } else if(docView){
      const dv=docView;
      const token=localStorage.getItem("authToken")||"";
      pageContent=(
        <div style={Z}>
          <div style={HH}>
            <button onClick={()=>setDocView(null)} style={BB}>←</button>
            <div style={{flex:1}}>
              <div style={{fontWeight:700,fontSize:17}}>{dv.storeName||"Dokument"}</div>
              <div style={{fontSize:12,color:"#94A3B8"}}>{docTypes.find(t=>t.id===dv.type)?.label} · {new Date(dv.createdAt).toLocaleDateString("de-DE",{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit"})}</div>
            </div>
          </div>
          <div style={{padding:"0 20px 100px"}}>
            {(dv.files||[]).map((f,i)=>(
              <div key={i} style={{marginBottom:12}}>
                <img src={"/api/docs/file/"+f+"?token="+token} style={{width:"100%",borderRadius:12,border:"1px solid #334155"}} onClick={()=>window.open("/api/docs/file/"+f+"?token="+token,"_blank")}/>
                <div style={{fontSize:11,color:"#64748B",marginTop:4,textAlign:"center"}}>Bild {i+1} von {dv.files.length} — antippen zum Vergrößern</div>
              </div>
            ))}
            {dv.note&&<div style={{...CC,marginTop:8}}><div style={{fontSize:12,color:"#64748B"}}>Notiz</div><div style={{fontSize:13,marginTop:4}}>{dv.note}</div></div>}
            <div style={{...CC,marginTop:8,fontSize:12,color:"#64748B"}}>
              <div>Hochgeladen von: {dv.userName}</div>
              <div>Filiale: {dv.storeName}</div>
            </div>
            <button onClick={async()=>{if(!confirm("Dokument wirklich löschen?"))return;try{const r=await fetch("/api/docs/"+dv.id,{method:"DELETE"});const j=await r.json();if(j.ok){setDocs(x=>x.filter(dd=>dd.id!==dv.id));setDocView(null)}}catch{}}} style={{width:"100%",marginTop:12,padding:"12px",background:"#7F1D1D",border:"1px solid #EF4444",borderRadius:10,color:"#FCA5A5",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>
              🗑 Dokument löschen
            </button>
          </div>
        </div>
      );
    } else {
      const renderDocItem=(d)=>(
        <div key={d.id} onClick={()=>setDocView(d)} style={{...CC,display:"flex",alignItems:"center",gap:10,marginBottom:8,cursor:"pointer"}}>
          <div style={{fontSize:22}}>{docTypes.find(t=>t.id===d.type)?.icon||"📄"}</div>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontWeight:600,fontSize:13}}>{d.storeName||"Unbekannt"}</div>
            <div style={{fontSize:11,color:"#94A3B8"}}>{docTypes.find(t=>t.id===d.type)?.label} · {new Date(d.createdAt).toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})}</div>
          </div>
          <div style={{display:"flex",alignItems:"center",gap:4}}>
            <span style={{fontSize:11,color:"#64748B"}}>{d.files?.length||0} 📷</span>
            <span style={{fontSize:14,color:"#334155"}}>›</span>
          </div>
        </div>
      );
      pageContent=(
        <div style={Z}>
          <div style={HH}>
            <button onClick={()=>setPage("home")} style={BB}>←</button>
            <div style={{flex:1}}><div style={{fontWeight:700,fontSize:17}}>📄 Dokumente</div></div>
          </div>
          <div style={{padding:"0 20px 100px"}}>
            <button onClick={()=>setPage("docUpload")} style={{width:"100%",padding:"14px",background:"linear-gradient(135deg, #3B82F6, #7C3AED)",border:"none",borderRadius:12,color:"white",fontSize:15,fontWeight:700,cursor:"pointer",fontFamily:"inherit",marginBottom:16}}>
              ＋ Neues Dokument hochladen
            </button>
            {todayDocs.length>0&&(
              <div style={{marginBottom:16}}>
                <div style={{fontSize:12,color:"#64748B",fontWeight:600,marginBottom:8}}>Heute</div>
                {todayDocs.map(renderDocItem)}
              </div>
            )}
            {olderDocs.length>0&&(
              <div>
                <div style={{fontSize:12,color:"#64748B",fontWeight:600,marginBottom:8}}>Früher</div>
                {olderDocs.slice(-20).reverse().map(renderDocItem)}
              </div>
            )}
            {docs.length===0&&(
              <div style={{textAlign:"center",padding:"40px 20px",color:"#64748B"}}>
                <div style={{fontSize:40,marginBottom:10}}>📄</div>
                <div style={{fontSize:14}}>Noch keine Dokumente</div>
                <div style={{fontSize:12,marginTop:4}}>Lade Anträge, Gehaltsnachweise etc. hoch</div>
              </div>
            )}
          </div>
        </div>
      );
    }
  }

  // ══════ DETAIL ══════
  if(page==="detail"&&sel){
    const s=sel,d=getData(s.id),cat=getCat(s.id),ci=CATS[cat]||CATS.besuchbar,vs=getVisits(s.id);
    pageContent=(
      <div style={Z}>
        <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
        <div style={HH}>
          <button onClick={()=>{setPage("list");setEditNote(false);setShowAV(false)}} style={BB}>←</button>
          <Logo employer={s.employer} size={44}/>
          <div style={{flex:1}}><div style={{fontWeight:700,fontSize:17}}>{s.name}</div><div style={{fontSize:12,color:"#94A3B8"}}>{s.employer} · {ci.icon} {ci.label}</div></div>
        </div>
        <div style={{padding:"0 20px 100px"}}>
          <div style={{...CC,marginTop:12}}>
            <div style={{fontSize:14,marginBottom:12}}>📍 {s.address}</div>
            <div style={{display:"flex",gap:8}}>
              <button onClick={()=>nav(s)} style={{flex:1,padding:"12px",background:"#3B82F6",color:"white",border:"none",borderRadius:10,fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>🧭 Nav</button>
              <button onClick={()=>window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(s.name+' '+s.address)}&query_place_id=${s.place_id}`,"_blank")} style={{flex:1,padding:"12px",background:"#334155",color:"#E2E8F0",border:"none",borderRadius:10,fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>📍 Maps</button>
              <button onClick={()=>setTour(t=>t.some(x=>x.id===s.id)?t.filter(x=>x.id!==s.id):[...t,s])} style={{flex:1,padding:"12px",background:tour.some(x=>x.id===s.id)?"#7C3AED":"#334155",color:tour.some(x=>x.id===s.id)?"white":"#C4B5FD",border:"none",borderRadius:10,fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>{tour.some(x=>x.id===s.id)?"✓ Tour":"+ Tour"}</button>
            </div>
          </div>
          <div style={{...CC,display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
            <div><div style={{fontSize:12,color:"#64748B"}}>Entfernung</div><div style={{fontWeight:700,color:"#60A5FA",fontSize:16}}>📍 {distStr(s)}</div></div>
            <div><div style={{fontSize:12,color:"#64748B"}}>VWL AG-Anteil</div><div style={{fontWeight:600,color:"#22C55E"}}>{s.vwl}</div></div>
            <div><div style={{fontSize:12,color:"#64748B"}}>Branche</div><div style={{fontWeight:600,fontSize:13}}>{s.branch}</div></div>
            <div><div style={{fontSize:12,color:"#64748B"}}>Bewertung</div><div style={{fontWeight:600}}>⭐ {s.rating}</div></div>
            <div><div style={{fontSize:12,color:"#64748B"}}>Öffnungszeiten</div><div style={{fontSize:13}}>{s.hours}</div></div>
            {d.lastVisit&&<div><div style={{fontSize:12,color:"#64748B"}}>Letzter Besuch</div><div style={{fontSize:13}}>{d.lastVisit}</div></div>}
          </div>
          <div style={CC}>
            <div style={{fontSize:13,color:"#94A3B8",marginBottom:10}}>Status</div>
            <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
              {Object.entries(CATS).map(([k,c])=>(<button key={k} onClick={()=>upd(s.id,{category:k,lastVisit:new Date().toLocaleDateString("de-DE")})} style={chip(cat===k,c.color)}>{c.icon} {c.label}</button>))}
            </div>
          </div>
          <div style={CC}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:showAV?12:0}}>
              <div style={{fontSize:14,fontWeight:600}}>📋 Historie ({vs.length})</div>
              <button onClick={()=>setShowAV(!showAV)} style={{padding:"6px 12px",background:showAV?"#EF4444":"#22C55E",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>{showAV?"✕":"+ Besuch"}</button>
            </div>
            {showAV&&(
              <div style={{background:"#0F172A",borderRadius:10,padding:14,marginBottom:12}}>
                <div style={{fontSize:12,color:"#64748B",marginBottom:8}}>Ergebnis</div>
                <div style={{display:"flex",gap:6,flexWrap:"wrap",marginBottom:12}}>
                  {Object.entries(CATS).map(([k,c])=>(<button key={k} onClick={()=>setVS(k)} style={chip(vS===k,c.color)}>{c.icon} {c.label}</button>))}
                </div>
                {vS==="abgelehnt"&&(<><div style={{fontSize:12,color:"#64748B",marginBottom:8}}>Einwand</div><div style={{display:"flex",gap:6,flexWrap:"wrap",marginBottom:12}}>{OBJS.map(o=>(<button key={o} onClick={()=>setVO(vO===o?"":o)} style={chip(vO===o,"#EF4444")}>{o}</button>))}</div></>)}
                <div style={{fontSize:12,color:"#64748B",marginBottom:6}}>Notiz</div>
                <textarea value={vN} onChange={e=>setVN(e.target.value)} placeholder="Was ist passiert?" rows={2} style={{...II,resize:"vertical",lineHeight:1.5}}/>
                <button onClick={()=>doAV(s.id)} style={{width:"100%",marginTop:12,padding:"12px",background:vS?"#22C55E":"#334155",color:"white",border:"none",borderRadius:10,fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>✓ Speichern</button>
              </div>
            )}
            {vs.length===0?<div style={{fontSize:13,color:"#475569",padding:"8px 0"}}>Noch keine Besuche.</div>:
              [...vs].reverse().map(v=>{const vc=CATS[v.status]||CATS.besuchbar;return(<div key={v.id} style={{borderLeft:`3px solid ${vc.color}`,paddingLeft:12,marginBottom:10,paddingBottom:8}}>
                <div style={{display:"flex",justifyContent:"space-between"}}><div style={{fontWeight:600,fontSize:13}}>{vc.icon} {vc.label}</div><div style={{fontSize:12,color:"#64748B"}}>{v.date} {v.time||""}</div></div>
                {v.contact&&<div style={{fontSize:12,color:"#60A5FA",marginTop:3}}>👤 {v.contact}</div>}
                {v.objection&&<div style={{fontSize:12,color:"#F87171",marginTop:3}}>🚫 {v.objection}</div>}
                {v.note&&<div style={{fontSize:12,color:"#94A3B8",marginTop:3}}>{v.note}</div>}
              </div>)})}
          </div>
          <div style={CC}>
            <div style={{fontSize:13,color:"#94A3B8",marginBottom:8}}>Filialverantwortlicher</div>
            <input defaultValue={d.contact||""} onBlur={e=>{if(e.target.value)upd(s.id,{contact:e.target.value})}} placeholder="Name..." style={{...II}}/>
          </div>
          {/* ═══ ABSCHLÜSSE / MITARBEITER (3 Slots) ═══ */}
          <div style={CC}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10}}>
              <div style={{fontSize:14,fontWeight:600}}>💸 Abschlüsse / Mitarbeiter</div>
              <div style={{fontSize:11,color:"#64748B"}}>{getClosures(s.id).filter(c=>c&&((c.nachname&&c.nachname.trim())||(c.vorname&&c.vorname.trim()))).length}/3</div>
            </div>
            <div style={{fontSize:11,color:"#64748B",marginBottom:8}}>Werden automatisch ins Tracking übernommen.</div>
            {[0,1,2].map(i=>{
              const c=getClosures(s.id)[i]||{};
              const filled=(c.nachname&&c.nachname.trim())||(c.vorname&&c.vorname.trim());
              return(
                <div key={i} style={{background:"#0F172A",borderRadius:10,padding:12,marginBottom:8,border:filled?"1px solid #22C55E":"1px solid #1E293B"}}>
                  <div style={{fontSize:11,fontWeight:700,color:filled?"#22C55E":"#64748B",marginBottom:8,letterSpacing:0.5}}>ABSCHLUSS {i+1}{filled?" ✓":""}</div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6,marginBottom:6}}>
                    <input defaultValue={c.vorname||""} onBlur={e=>updateClosure(s.id,i,{vorname:e.target.value})} placeholder="Vorname" style={{...II,fontSize:13,padding:"8px 10px"}}/>
                    <input defaultValue={c.nachname||""} onBlur={e=>updateClosure(s.id,i,{nachname:e.target.value})} placeholder="Nachname" style={{...II,fontSize:13,padding:"8px 10px"}}/>
                  </div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6,marginBottom:8}}>
                    <div>
                      <div style={{fontSize:10,color:"#64748B",marginBottom:3,fontWeight:600}}>Datum</div>
                      <input type="date" defaultValue={c.datum||new Date().toISOString().slice(0,10)} onBlur={e=>updateClosure(s.id,i,{datum:e.target.value})} style={{...II,fontSize:13,padding:"8px 10px"}}/>
                    </div>
                    <div>
                      <div style={{fontSize:10,color:"#64748B",marginBottom:3,fontWeight:600}}>Bausparsumme €</div>
                      <input defaultValue={c.bausparsumme||""} onBlur={e=>updateClosure(s.id,i,{bausparsumme:e.target.value})} placeholder="z.B. 25.000" style={{...II,fontSize:13,padding:"8px 10px"}}/>
                    </div>
                  </div>
                  <div style={{fontSize:11,color:"#64748B",marginBottom:4}}>Persönlichkeitstyp</div>
                  <div style={{display:"flex",gap:4,flexWrap:"wrap",marginBottom:8}}>
                    {PTYPES.map(t=>(<button key={t} onClick={()=>updateClosure(s.id,i,{personType:c.personType===t?"":t})} style={{...chip(c.personType===t,t==="Sehr unfreundlich"?"#EF4444":"#3B82F6"),fontSize:10,padding:"4px 8px"}}>{t}</button>))}
                  </div>
                  <textarea defaultValue={c.notes||""} onBlur={e=>updateClosure(s.id,i,{notes:e.target.value})} placeholder="Notiz zur Person (z.B. skeptisch, Familie, …)" rows={2} style={{...II,fontSize:13,padding:"8px 10px",resize:"vertical",lineHeight:1.4}}/>
                </div>
              );
            })}
          </div>
          <div style={CC}>
            <div style={{fontSize:13,color:"#94A3B8",marginBottom:8}}>Persönlichkeitstyp (Filiale insgesamt)</div>
            <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>{PTYPES.map(t=>(<button key={t} onClick={()=>upd(s.id,{personType:t})} style={chip(d.personType===t,t==="Sehr unfreundlich"?"#EF4444":"#3B82F6")}>{t}</button>))}</div>
          </div>
          <div style={CC}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10}}>
              <div style={{fontSize:14,fontWeight:600}}>📝 Notizen</div>
              <button onClick={()=>{if(editNote){upd(s.id,{notes:noteText});setEditNote(false)}else{setNoteText(d.notes||"");setEditNote(true);setTimeout(()=>noteRef.current?.focus(),50)}}}
                style={{padding:"6px 14px",background:editNote?"#22C55E":"#334155",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>{editNote?"✓ Speichern":"✎ Bearbeiten"}</button>
            </div>
            {editNote?<textarea ref={noteRef} value={noteText} onChange={e=>setNoteText(e.target.value)} placeholder="z.B. Lisa hat Hund Max..." style={{...II,minHeight:100,resize:"vertical",lineHeight:1.5}}/>
              :<div style={{padding:12,background:"#0F172A",borderRadius:8,minHeight:50,fontSize:13,color:d.notes?"#E2E8F0":"#475569",lineHeight:1.6,whiteSpace:"pre-wrap"}}>{d.notes||"Noch keine Notizen."}</div>}
          </div>
        </div>
      </div>
    );
  }

  // ══════ MAP ══════
  if(page==="map"){
    const locateMe=()=>{
      if(!mapInst.current)return;
      setPlanLoc(null);setMapSearch("");setSearchResults([]);
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(pos=>{
          mapInst.current.flyTo([pos.coords.latitude,pos.coords.longitude],15,{duration:1});
        },()=>{
          mapInst.current.flyTo([49.4925,9.7744],14,{duration:1});
        },{enableHighAccuracy:true,timeout:5000});
      } else {
        mapInst.current.flyTo([49.4925,9.7744],14,{duration:1});
      }
    };
    const doSearch=async()=>{
      const q=(mapSearch||"").trim();
      if(!q)return;
      // 1) Erst lokale Filialen prüfen (Lidl, Aldi, ...)
      const sq=q.toLowerCase();
      const src=allStores.length>0?allStores:stores;
      const localHit=src.some(s=>(s.name||"").toLowerCase().includes(sq)||(s.employer||"").toLowerCase().includes(sq));
      if(localHit){
        setMapStoreF(q);
        setSearchResults([]);
        // Auf Treffer zoomen
        setTimeout(()=>{
          if(!mapInst.current||!window.L)return;
          const matches=src.filter(s=>(s.name||"").toLowerCase().includes(sq)||(s.employer||"").toLowerCase().includes(sq));
          if(matches.length===0)return;
          const bounds=window.L.latLngBounds(matches.map(s=>[s.lat,s.lng]));
          mapInst.current.fitBounds(bounds.pad(0.2),{maxZoom:14});
        },200);
        return;
      }
      // 2) Sonst Ortssuche per Nominatim
      try{
        const res=await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=5&countrycodes=de&accept-language=de`);
        setSearchResults(await res.json());
      }catch(e){}
    };
    const pickResult=(r)=>{
      const loc={lat:parseFloat(r.lat),lng:parseFloat(r.lon),name:r.display_name.split(",")[0]};
      setPlanLoc(loc);setSearchResults([]);setMapSearch("");
      if(mapInst.current)mapInst.current.flyTo([loc.lat,loc.lng],13,{duration:1});
    };
    pageContent=(
    <div style={{...Z,height:"100dvh",overflow:"hidden",display:"flex",flexDirection:"column",paddingBottom:0}}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
      <style>{`.leaflet-tile-pane,.leaflet-zoom-animated{will-change:transform;transform:translateZ(0)}.leaflet-container{-webkit-tap-highlight-color:transparent;-webkit-overflow-scrolling:touch;touch-action:none}html,body{overscroll-behavior:none}`}</style>
      <div style={{...HH,gap:8,flexShrink:0}}><button onClick={()=>setPage("home")} style={BB}>←</button><div style={{fontWeight:700,fontSize:17,flex:1}}>🗺 Karte</div><GpsToggle/></div>
      <div style={{background:"#0F172A",borderBottom:"1px solid #1E293B",padding:"8px 12px",flexShrink:0}}>
        <div style={{display:"flex",gap:6,marginBottom:6}}>
          <input value={mapSearch} onChange={e=>setMapSearch(e.target.value)} onKeyDown={e=>{if(e.key==="Enter")doSearch()}} placeholder="🔍 Laden oder Ort suchen…" style={{...II,flex:1,borderRadius:12,padding:"9px 14px",fontSize:13}}/>
          <button onClick={doSearch} style={{padding:"8px 14px",background:"#3B82F6",border:"none",borderRadius:12,color:"white",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap"}}>Los</button>
          {planLoc&&<button onClick={()=>{setPlanLoc(null);setMapSearch("")}} style={{padding:"8px 12px",background:"#7C3AED",border:"none",borderRadius:12,color:"white",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap"}}>✕ GPS</button>}
        </div>
        {searchResults.length>0&&<div style={{background:"#1E293B",borderRadius:10,marginBottom:6,overflow:"hidden",border:"1px solid #334155"}}>
          {searchResults.map(r=>(<div key={r.place_id} onClick={()=>pickResult(r)} style={{padding:"10px 12px",borderBottom:"1px solid #0F172A",cursor:"pointer",fontSize:12,color:"#E2E8F0"}}>{r.display_name}</div>))}
        </div>}
        {mapStoreF&&<div style={{display:"flex",alignItems:"center",gap:6,marginBottom:6,padding:"6px 10px",background:"#3B82F622",borderRadius:8,border:"1px solid #3B82F6"}}>
          <span style={{fontSize:14}}>🔍</span>
          <span style={{fontSize:12,color:"#93C5FD",flex:1}}>Ladenfilter: <b style={{color:"#E2E8F0"}}>{mapStoreF}</b></span>
          <button onClick={()=>{setMapStoreF("");setMapSearch("")}} style={{padding:"3px 10px",background:"#3B82F6",border:"none",borderRadius:8,color:"white",fontSize:11,fontWeight:700,cursor:"pointer",fontFamily:"inherit"}}>✕</button>
        </div>}
        {planLoc&&<div style={{display:"flex",alignItems:"center",gap:6,marginBottom:6,padding:"6px 10px",background:"#7C3AED22",borderRadius:8,border:"1px solid #7C3AED"}}>
          <span style={{fontSize:14}}>📍</span><span style={{fontSize:12,color:"#C4B5FD",flex:1}}>Planung: <b style={{color:"#E2E8F0"}}>{planLoc.name}</b></span>
        </div>}
        <div style={{display:"flex",gap:6,overflowX:"auto",marginBottom:6}}>
          <button onClick={()=>setMapBranchF("all")} style={chip(mapBranchF==="all","#64748B")}>Alle Branchen</button>
          <button onClick={()=>setMapBranchF(mapBranchF==="supermarkt"?"all":"supermarkt")} style={chip(mapBranchF==="supermarkt","#22C55E")}>🛒 Supermärkte</button>
          <button onClick={()=>setMapBranchF(mapBranchF==="baumarkt"?"all":"baumarkt")} style={chip(mapBranchF==="baumarkt","#F59E0B")}>🧰 Baumärkte</button>
        </div>
        <div style={{display:"flex",gap:6,overflowX:"auto"}}>
          {(()=>{const src=allStores.length>0?allStores:stores;const mst={};["besuchbar","drin","geschrieben","abgelehnt"].forEach(k=>{mst[k]=src.filter(s=>getCat(s.id)===k).length});mst.total=src.length;return(<>
            <button onClick={()=>setMF("all")} style={chip(mf==="all","#3B82F6")}>Alle ({mst.total})</button>
            {Object.entries(CATS).map(([k,c])=>(<button key={k} onClick={()=>setMF(k)} style={chip(mf===k,c.color)}>{c.icon} {mst[k]||0}</button>))}
          </>)})()}
        </div>
      </div>
      <div style={{position:"relative",flex:1,overflow:"hidden"}}>
        <div ref={mapRef} style={{height:"100%",width:"100%",background:"#F0EDE6"}}/>
        <button onClick={locateMe} style={{position:"absolute",bottom:70,right:14,zIndex:1000,width:46,height:46,borderRadius:"50%",background:planLoc?"#7C3AED":"white",border:"none",boxShadow:"0 2px 8px rgba(0,0,0,0.25)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" fill={planLoc?"white":"#4285F4"}/><circle cx="12" cy="12" r="8" stroke={planLoc?"white":"#4285F4"} strokeWidth="2" fill="none"/><line x1="12" y1="0" x2="12" y2="4" stroke={planLoc?"white":"#4285F4"} strokeWidth="2"/><line x1="12" y1="20" x2="12" y2="24" stroke={planLoc?"white":"#4285F4"} strokeWidth="2"/><line x1="0" y1="12" x2="4" y2="12" stroke={planLoc?"white":"#4285F4"} strokeWidth="2"/><line x1="20" y1="12" x2="24" y2="12" stroke={planLoc?"white":"#4285F4"} strokeWidth="2"/></svg>
        </button>
        <button onClick={()=>{if(mapInst.current&&mapInst.current.setBearing)mapInst.current.setBearing(0)}} title="Norden ausrichten" style={{position:"absolute",bottom:124,right:14,zIndex:1000,width:46,height:46,borderRadius:"50%",background:"white",border:"none",boxShadow:"0 2px 8px rgba(0,0,0,0.25)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"#EF4444",fontFamily:"system-ui"}}>
          🧭
        </button>
      </div>
    </div>
  )}

  // ══════ TOUR ══════
  if(page==="tour"){
    const addTour=s=>setTour(t=>t.some(x=>x.id===s.id)?t:[...t,s]);
    const rmTour=id=>setTour(t=>t.filter(x=>x.id!==id));
    const mvUp=i=>{if(i===0)return;setTour(t=>{const n=[...t];[n[i-1],n[i]]=[n[i],n[i-1]];return n})};
    const mvDown=i=>{if(i>=tour.length-1)return;setTour(t=>{const n=[...t];[n[i],n[i+1]]=[n[i+1],n[i]];return n})};
    const optimizeRoute=()=>{
      if(tour.length<3)return;
      haptic(15);
      const loc=planLoc||userLoc;
      const remaining=[...tour];const sorted=[];
      let cur={lat:loc.lat,lng:loc.lng};
      while(remaining.length>0){
        let nearest=0,minD=Infinity;
        remaining.forEach((s,i)=>{const d=getDist(cur.lat,cur.lng,s.lat,s.lng);if(d<minD){minD=d;nearest=i}});
        sorted.push(remaining.splice(nearest,1)[0]);
        cur=sorted[sorted.length-1];
      }
      setTour(sorted);
    };

    let totalDist=0;
    const loc=planLoc||userLoc;
    if(tour.length>0){
      totalDist+=getDist(loc.lat,loc.lng,tour[0].lat,tour[0].lng);
      for(let i=1;i<tour.length;i++)totalDist+=getDist(tour[i-1].lat,tour[i-1].lng,tour[i].lat,tour[i].lng);
    }
    const estMin=Math.round(totalDist/40*60);

    const startRoute=()=>{
      if(tour.length===0)return;
      const origin=`${loc.lat},${loc.lng}`;
      const dest=tour[tour.length-1];
      if(tour.length===1){
        window.open(`https://www.google.com/maps/dir/?api=1&origin=${origin}&destination=${dest.lat},${dest.lng}&travelmode=driving`,"_blank");
      }else{
        const wps=tour.slice(0,-1).map(s=>`${s.lat},${s.lng}`).join("|");
        window.open(`https://www.google.com/maps/dir/?api=1&origin=${origin}&destination=${dest.lat},${dest.lng}&waypoints=${wps}&travelmode=driving`,"_blank");
      }
    };

    pageContent=(
      <div style={Z}>
        <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
        <div style={HH}>
          <button onClick={()=>setPage("home")} style={BB}>←</button>
          <div style={{flex:1,fontWeight:700,fontSize:20}}>🧭 Tourenplaner</div>
          {tour.length>=3&&<button onClick={optimizeRoute} style={{padding:"6px 12px",background:"#3B82F622",border:"1px solid #3B82F6",borderRadius:8,color:"#3B82F6",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>⚡ Optimieren</button>}
          {tour.length>0&&<button onClick={()=>setTour([])} style={{padding:"6px 12px",background:"#334155",border:"none",borderRadius:8,color:"#EF4444",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>Leeren</button>}
        </div>
        <div style={{padding:"16px 20px 100px"}}>
          {tour.length===0?(
            <div style={{textAlign:"center",padding:40,color:"#64748B"}}>
              <div style={{fontSize:48}}>🧭</div>
              <div style={{marginTop:12,fontSize:15,fontWeight:600,color:"#E2E8F0"}}>Noch keine Läden geplant</div>
              <div style={{marginTop:6,fontSize:13}}>Tippe auf <span style={{color:"#7C3AED",fontWeight:700}}>+</span> in der Liste um Läden zur Tour hinzuzufügen</div>
              <button onClick={()=>setPage("list")} style={{marginTop:16,padding:"10px 24px",background:"#3B82F6",border:"none",borderRadius:10,color:"white",fontSize:14,fontWeight:700,cursor:"pointer",fontFamily:"inherit"}}>📋 Zur Liste</button>
            </div>
          ):(
            <>
              <div style={{...CC,border:"1px solid #334155",display:"flex",justifyContent:"space-around",textAlign:"center",marginBottom:16}}>
                <div><div style={{fontSize:22,fontWeight:700,color:"#7C3AED"}}>{tour.length}</div><div style={{fontSize:11,color:"#94A3B8"}}>Stops</div></div>
                <div><div style={{fontSize:22,fontWeight:700,color:"#3B82F6"}}>{totalDist<1?(totalDist*1000).toFixed(0)+" m":totalDist.toFixed(1)+" km"}</div><div style={{fontSize:11,color:"#94A3B8"}}>Strecke</div></div>
                <div><div style={{fontSize:22,fontWeight:700,color:"#F97316"}}>{estMin<60?estMin+" min":Math.floor(estMin/60)+"h "+estMin%60+"m"}</div><div style={{fontSize:11,color:"#94A3B8"}}>ca. Fahrzeit</div></div>
              </div>
              {tour.map((s,i)=>{
                const cat=getCat(s.id),ci=CATS[cat]||CATS.besuchbar;
                return(
                <div key={s.id} style={{display:"flex",alignItems:"center",gap:8,background:"#1E293B",borderRadius:12,padding:12,marginBottom:8,borderLeft:`4px solid ${ci.color}`}}>
                  <div style={{fontSize:18,fontWeight:800,color:"#7C3AED",width:22,textAlign:"center",flexShrink:0}}>{i+1}</div>
                  <Logo employer={s.employer} size={34}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontWeight:700,fontSize:13}}>{s.name}</div>
                    <div style={{fontSize:11,color:"#94A3B8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{s.address}</div>
                    <div style={{fontSize:10,color:"#64748B",marginTop:2}}>{s.branch} · {s.vwl}</div>
                  </div>
                  <div style={{display:"flex",flexDirection:"column",gap:2,flexShrink:0}}>
                    <button onClick={()=>mvUp(i)} style={{width:26,height:22,background:i===0?"#0F172A":"#334155",border:"none",borderRadius:4,color:i===0?"#475569":"#E2E8F0",fontSize:12,cursor:"pointer",fontFamily:"inherit"}}>▲</button>
                    <button onClick={()=>mvDown(i)} style={{width:26,height:22,background:i>=tour.length-1?"#0F172A":"#334155",border:"none",borderRadius:4,color:i>=tour.length-1?"#475569":"#E2E8F0",fontSize:12,cursor:"pointer",fontFamily:"inherit"}}>▼</button>
                  </div>
                  <button onClick={()=>rmTour(s.id)} style={{width:28,height:28,background:"#EF444422",border:"1px solid #EF4444",borderRadius:6,color:"#EF4444",fontSize:13,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontFamily:"inherit"}}>✕</button>
                </div>
              )})}
              <button onClick={startRoute} style={{width:"100%",padding:"14px",background:"#22C55E",border:"none",borderRadius:12,color:"white",fontSize:16,fontWeight:700,cursor:"pointer",fontFamily:"inherit",marginTop:8,boxShadow:"0 4px 12px rgba(34,197,94,0.3)"}}>
                🧭 Route starten ({tour.length} Stops)
              </button>
            </>
          )}
        </div>
      </div>
    );
  }

  // ══════ STATS ══════
  if(page==="stats"){
    const now=new Date();
    const parseDE=ds=>{if(!ds)return null;const p=ds.split(".");if(p.length===3)return new Date(p[2],p[1]-1,p[0]);return null};
    const dayOW=now.getDay()||7;
    const weekStart=new Date(now);weekStart.setDate(now.getDate()-dayOW+1);weekStart.setHours(0,0,0,0);
    const monthStart=new Date(now.getFullYear(),now.getMonth(),1);
    const yearStart=new Date(now.getFullYear(),0,1);
    const periodStart=statsPeriod==="W"?weekStart:statsPeriod==="M"?monthStart:yearStart;

    const allVisits=[];
    stores.forEach(s=>{(getData(s.id).visits||[]).forEach(v=>{const vd=parseDE(v.date);if(vd&&vd>=periodStart)allVisits.push({...v,storeId:s.id,_date:vd})})});

    const pSt={drin:0,geschrieben:0,abgelehnt:0,besuchbar:0,total:0};
    allVisits.forEach(v=>{if(v.status&&pSt.hasOwnProperty(v.status))pSt[v.status]++});
    pSt.total=allVisits.length;

    const reinQ=(pSt.drin+pSt.abgelehnt)>0?((pSt.drin/(pSt.drin+pSt.abgelehnt))*100):0;
    const abschlQ=(pSt.drin+pSt.geschrieben)>0?((pSt.geschrieben/(pSt.drin+pSt.geschrieben))*100):0;

    let umsatz=0;
    const geschriebenIds=new Set();
    allVisits.forEach(v=>{if(v.status==="geschrieben")geschriebenIds.add(v.storeId)});
    stores.forEach(s=>{if(geschriebenIds.has(s.id)&&s.vwl&&s.vwl.includes("€")){const v=parseFloat(s.vwl.replace(/[^0-9,]/g,"").replace(",","."));if(!isNaN(v))umsatz+=v}});

    const visitDays=new Set();
    stores.forEach(s=>{(getData(s.id).visits||[]).forEach(v=>{if(v.date)visitDays.add(v.date)})});

    const streakDays=[];
    for(let i=6;i>=0;i--){const d=new Date(now.getTime()-i*86400000);const ds=d.toLocaleDateString("de-DE");streakDays.push({day:["So","Mo","Di","Mi","Do","Fr","Sa"][d.getDay()],active:visitDays.has(ds)})}
    let streak=0;for(let i=streakDays.length-1;i>=0;i--){if(streakDays[i].active)streak++;else if(streak>0)break}

    const branchCounts={};
    const periodStoreIds=new Set();
    allVisits.forEach(v=>{if(v.status==="drin"||v.status==="geschrieben")periodStoreIds.add(v.storeId)});
    stores.forEach(s=>{if(periodStoreIds.has(s.id)){const b=s.branch||"Sonstige";branchCounts[b]=(branchCounts[b]||0)+1}});
    const topBranches=Object.entries(branchCounts).sort((a,b)=>b[1]-a[1]).slice(0,4);
    const maxB=topBranches[0]?.[1]||1;

    const sparkN=statsPeriod==="W"?7:statsPeriod==="M"?(new Date(now.getFullYear(),now.getMonth()+1,0).getDate()):12;
    const sparkData=[];
    if(statsPeriod==="J"){
      for(let m=0;m<12;m++){let c=0;allVisits.forEach(v=>{if(v._date.getMonth()===m)c++});sparkData.push(c)}
    }else{
      for(let i=sparkN-1;i>=0;i--){const d=new Date(now.getTime()-i*86400000);const ds=d.toLocaleDateString("de-DE");let c=0;stores.forEach(s=>{(getData(s.id).visits||[]).forEach(v=>{if(v.date===ds)c++})});sparkData.push(c)}
    }
    const sparkMax=Math.max(...sparkData,1);
    const sparkW=Math.min(96,sparkN*13);
    const sparkStep=(sparkW-8)/(sparkData.length-1||1);
    const sparkPts=sparkData.map((v,i)=>`${4+i*sparkStep},${32-(v/sparkMax)*26}`).join(" ");

    const sun=new Date(weekStart);sun.setDate(weekStart.getDate()+6);
    const wn=Math.ceil(((now-new Date(now.getFullYear(),0,1))/86400000+new Date(now.getFullYear(),0,1).getDay()+1)/7);
    const periodLabel=statsPeriod==="W"?`Woche ${wn} · ${weekStart.getDate()}.–${sun.getDate()}. ${sun.toLocaleDateString("de-DE",{month:"short"})}`:statsPeriod==="M"?now.toLocaleDateString("de-DE",{month:"long",year:"numeric"}):now.getFullYear()+"";

    const fData=[{label:"Besuche",count:pSt.total,color:"#F97316"},{label:"Reingekommen",count:pSt.drin+pSt.geschrieben,color:"#3B82F6"},{label:"Geschrieben",count:pSt.geschrieben,color:"#8B5CF6"}];
    const fMax=Math.max(...fData.map(f=>f.count),1);

    pageContent=(
      <div style={Z}>
        <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
        <div style={HH}>
          <button onClick={()=>setPage("home")} style={BB}>←</button>
          <div style={{flex:1,fontWeight:700,fontSize:20}}>Performance</div>
          <div style={{display:"flex",gap:4}}>
            {["W","M","J"].map(p=>(<button key={p} onClick={()=>setStatsPeriod(p)} style={{padding:"6px 12px",borderRadius:8,border:"none",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"inherit",background:statsPeriod===p?"#3B82F6":"#1E293B",color:statsPeriod===p?"white":"#64748B"}}>{p}</button>))}
          </div>
        </div>
        <div style={{padding:"4px 20px 0",color:"#64748B",fontSize:13}}>{periodLabel}</div>
        <div style={{padding:"12px 20px 100px"}}>

          <div style={{...CC,border:"1px solid #334155",overflow:"hidden"}}>
            <div style={{fontSize:11,fontWeight:700,color:"#F97316",letterSpacing:1,marginBottom:4}}>ABSCHLUSSQUOTE</div>
            <div style={{display:"flex",alignItems:"center",gap:12}}>
              <div style={{fontSize:42,fontWeight:700}}>{abschlQ.toFixed(1).replace(".",",")} %</div>
              <svg width="96" height="36" viewBox="0 0 96 36" style={{flexShrink:0}}>
                <polyline points={sparkPts} fill="none" stroke="#22C55E" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                {sparkData.map((v,i)=><circle key={i} cx={4+i*sparkStep} cy={32-(v/sparkMax)*26} r="2.5" fill="#22C55E"/>)}
              </svg>
            </div>
            <div style={{fontSize:12,color:"#22C55E",marginTop:4}}>📊 {pSt.geschrieben} von {pSt.drin+pSt.geschrieben} abgeschlossen</div>
            <div style={{marginTop:16,display:"flex",flexDirection:"column",gap:6}}>
              {fData.map(f=>(<div key={f.label} style={{display:"flex",alignItems:"center",gap:8}}>
                <div style={{width:90,fontSize:11,color:"#94A3B8",textAlign:"right"}}>{f.label}</div>
                <div style={{flex:1,height:20,background:"#0F172A",borderRadius:6,overflow:"hidden"}}>
                  <div style={{height:"100%",width:`${(f.count/fMax)*100}%`,background:f.color,borderRadius:6,transition:"width 0.5s"}}/>
                </div>
                <div style={{width:30,fontSize:13,fontWeight:700,color:f.color,textAlign:"right"}}>{f.count}</div>
              </div>))}
            </div>
          </div>

          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:10}}>
            <div style={{...CC,textAlign:"center",border:"1px solid #334155"}}>
              <div style={{fontSize:11,color:"#94A3B8",marginBottom:4}}>Reinkommquote</div>
              <div style={{fontSize:28,fontWeight:700,color:"#3B82F6"}}>{reinQ.toFixed(1).replace(".",",")}%</div>
              <div style={{fontSize:11,color:"#64748B",marginTop:2}}>{pSt.drin} von {pSt.drin+pSt.abgelehnt}</div>
            </div>
            <div style={{...CC,textAlign:"center",border:"1px solid #334155"}}>
              <div style={{fontSize:11,color:"#94A3B8",marginBottom:4}}>Umsatz (VWL)</div>
              <div style={{fontSize:28,fontWeight:700,color:"#22C55E"}}>{umsatz.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g,".")} €</div>
              <div style={{fontSize:11,color:"#64748B",marginTop:2}}>{pSt.geschrieben} Verträge</div>
            </div>
          </div>

          {topBranches.length>0&&<div style={{...CC,border:"1px solid #334155"}}>
            <div style={{fontSize:14,fontWeight:700,marginBottom:12}}>Top Kategorien</div>
            {topBranches.map(([branch,count])=>(<div key={branch} style={{marginBottom:8}}>
              <div style={{display:"flex",justifyContent:"space-between",fontSize:12,marginBottom:3}}>
                <span style={{color:"#E2E8F0"}}>{branch}</span>
                <span style={{color:"#94A3B8",fontWeight:600}}>{count}</span>
              </div>
              <div style={{height:8,background:"#0F172A",borderRadius:4,overflow:"hidden"}}>
                <div style={{height:"100%",width:`${(count/maxB)*100}%`,background:"linear-gradient(90deg,#F97316,#FB923C)",borderRadius:4}}/>
              </div>
            </div>))}
          </div>}

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:12}}>
              <span style={{fontSize:22}}>🔥</span>
              <div>
                <div style={{fontSize:14,fontWeight:700}}>{streak}-Tage-Streak</div>
                <div style={{fontSize:11,color:"#64748B"}}>Letzte 7 Tage mit Besuchen</div>
              </div>
            </div>
            <div style={{display:"flex",gap:6,justifyContent:"space-between"}}>
              {streakDays.map((d,i)=>(<div key={i} style={{flex:1,textAlign:"center"}}>
                <div style={{height:32,background:d.active?"#F97316":"#1E293B",borderRadius:6,marginBottom:4,border:d.active?"none":"1px solid #334155"}}/>
                <div style={{fontSize:10,color:d.active?"#F97316":"#64748B",fontWeight:d.active?700:400}}>{d.day}</div>
              </div>))}
            </div>
          </div>

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12}}>
              <div style={{fontSize:14,fontWeight:700}}>Level & XP</div>
              <div style={{fontSize:13,fontWeight:700,color:"#C4B5FD"}}>{lvl.icon} {lvl.name}</div>
            </div>
            <div style={{display:"flex",alignItems:"baseline",gap:6,marginBottom:8}}>
              <div style={{fontSize:28,fontWeight:700,color:"#7C3AED"}}>{xp}</div>
              <div style={{fontSize:12,color:"#94A3B8"}}>XP {nxtLvl?`· ${nxtLvl.min-xp} bis ${nxtLvl.icon} ${nxtLvl.name}`:""}</div>
            </div>
            <div style={{height:8,background:"#0F172A",borderRadius:4,overflow:"hidden"}}>
              <div style={{height:"100%",width:`${lvlProg*100}%`,background:"linear-gradient(90deg,#7C3AED,#A78BFA)",borderRadius:4,transition:"width 0.5s"}}/>
            </div>
            <div style={{display:"flex",justifyContent:"space-between",fontSize:10,color:"#64748B",marginTop:4}}>
              <span>{lvl.icon} {lvl.min} XP</span>
              {nxtLvl&&<span>{nxtLvl.icon} {nxtLvl.min} XP</span>}
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,marginTop:12,fontSize:11,textAlign:"center"}}>
              <div style={{background:"#0F172A",borderRadius:8,padding:8}}><div style={{fontWeight:700,color:"#60A5FA"}}>{allV}</div><div style={{color:"#64748B"}}>Besuche</div></div>
              <div style={{background:"#0F172A",borderRadius:8,padding:8}}><div style={{fontWeight:700,color:"#3B82F6"}}>{allD}</div><div style={{color:"#64748B"}}>Rein</div></div>
              <div style={{background:"#0F172A",borderRadius:8,padding:8}}><div style={{fontWeight:700,color:"#22C55E"}}>{allG}</div><div style={{color:"#64748B"}}>Verträge</div></div>
            </div>
          </div>

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{fontSize:14,fontWeight:700,marginBottom:12}}>Auszeichnungen ({BADGES.filter(b=>b.need).length}/{BADGES.length})</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8}}>
              {BADGES.map(b=>{const hidden=b.secret&&!b.need;return(<div key={b.id} style={{background:b.need?"#0F172A":"#080E1A",borderRadius:10,padding:10,textAlign:"center",opacity:b.need?1:0.35,border:b.need?(b.secret?"1px solid #F59E0B":"1px solid #334155"):"1px solid #1E293B"}}>
                <div style={{fontSize:24}}>{hidden?"🔒":b.icon}</div>
                <div style={{fontSize:10,fontWeight:600,color:b.need?(b.secret?"#F59E0B":"#E2E8F0"):"#475569",marginTop:2}}>{hidden?"???":b.name}</div>
                <div style={{fontSize:9,color:"#64748B"}}>{hidden?"Geheim":b.desc}</div>
              </div>)})}
            </div>
          </div>

          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
            {Object.entries(CATS).map(([k,c])=>(<div key={k} style={{...CC,textAlign:"center",border:"1px solid #334155"}}>
              <div style={{fontSize:24}}>{c.icon}</div>
              <div style={{fontSize:24,fontWeight:700,color:c.color}}>{pSt[k]||0}</div>
              <div style={{fontSize:11,color:"#94A3B8"}}>{c.label}</div>
            </div>))}
          </div>

        </div>
      </div>
    );
  }

  // ══════ EINSTELLUNGEN ══════
  if(page==="settings"){
    const BRANCHES=["🛒 Supermarkt","💄 Kosmetik","🏢 Elektronik","🧰 Baumarkt","👕 Mode","👓 Optiker","🚗 Auto","🍔 Gastronomie","🏘️ Heim/Möbel","⚽ Sport","📚 Bücher","🪴 Gartencenter","🏢 Sonstige"];
    const submitEmployer=async()=>{
      if(!empForm.name.trim())return;
      try{
        const res=await fetch('/api/employer-suggestions',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(empForm)});
        const j=await res.json();
        if(j.success){setEmpSent(true);setEmpForm({name:"",branche:"",vwl:"",address:"",contact:"",notes:"",website:""});setTimeout(()=>setEmpSent(false),4000)}
      }catch(e){}
    };
    const privacyDate=localStorage.getItem("privacyAccepted");
    pageContent=(
      <div style={Z}>
        <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
        <div style={HH}>
          <button onClick={()=>setPage("home")} style={BB}>←</button>
          <div style={{flex:1}}>
            <div style={{fontWeight:700,fontSize:20}}>Einstellungen</div>
            {currentUser&&<div style={{fontSize:12,color:"#94A3B8"}}>{currentUser.name} · {currentUser.role==="admin"?"Admin":"Partner"}</div>}
          </div>
        </div>
        <div style={{padding:"12px 20px 100px"}}>

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12}}>
              <div style={{fontSize:16,fontWeight:700}}>Mein Profil</div>
              <button onClick={()=>{if(profileEdit){saveProfile()}else{setProfileForm({name:currentUser.name||"",region:currentUser.region||"",phone:currentUser.phone||"",email:currentUser.email||"",newPin:""});setProfileEdit(true)}}} style={{padding:"6px 14px",background:profileEdit?"#22C55E":"#334155",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>
                {profileEdit?"✓ Speichern":"✎ Bearbeiten"}
              </button>
            </div>
            {profileEdit?(
              <div style={{display:"flex",flexDirection:"column",gap:10}}>
                <div><div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Name</div><input value={profileForm.name||""} onChange={e=>setProfileForm({...profileForm,name:e.target.value})} style={II}/></div>
                <div><div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Region</div><input value={profileForm.region||""} onChange={e=>setProfileForm({...profileForm,region:e.target.value})} placeholder="z.B. Würzburg / Main-Tauber" style={II}/></div>
                <div><div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Telefon</div><input value={profileForm.phone||""} onChange={e=>setProfileForm({...profileForm,phone:e.target.value})} placeholder="z.B. 0171 1234567" style={II}/></div>
                <div><div style={{fontSize:12,color:"#64748B",marginBottom:4}}>E-Mail</div><input value={profileForm.email||""} onChange={e=>setProfileForm({...profileForm,email:e.target.value})} placeholder="z.B. max@beispiel.de" style={II}/></div>
                <div><div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Neuer PIN (leer lassen = nicht ändern)</div><input value={profileForm.newPin||""} onChange={e=>setProfileForm({...profileForm,newPin:e.target.value.replace(/[^0-9]/g,"")})} type="password" inputMode="numeric" maxLength={6} placeholder="Neuen PIN eingeben" style={II}/></div>
              </div>
            ):(
              <div style={{display:"flex",flexDirection:"column",gap:8,fontSize:13,color:"#94A3B8"}}>
                <div style={{display:"flex",justifyContent:"space-between"}}><span>Name</span><span style={{color:"#E2E8F0",fontWeight:600}}>{currentUser.name}</span></div>
                <div style={{display:"flex",justifyContent:"space-between"}}><span>Rolle</span><span style={{color:currentUser.role==="admin"?"#F59E0B":"#3B82F6",fontWeight:600}}>{currentUser.role==="admin"?"Admin":"Partner"}</span></div>
                {currentUser.region&&<div style={{display:"flex",justifyContent:"space-between"}}><span>Region</span><span style={{color:"#E2E8F0",fontWeight:600}}>{currentUser.region}</span></div>}
                {currentUser.phone&&<div style={{display:"flex",justifyContent:"space-between"}}><span>Telefon</span><span style={{color:"#E2E8F0",fontWeight:600}}>{currentUser.phone}</span></div>}
                {currentUser.email&&<div style={{display:"flex",justifyContent:"space-between"}}><span>E-Mail</span><span style={{color:"#E2E8F0",fontWeight:600}}>{currentUser.email}</span></div>}
              </div>
            )}
          </div>

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{fontSize:16,fontWeight:700,marginBottom:14}}>Neuen Arbeitgeber melden</div>
            <div style={{fontSize:12,color:"#94A3B8",marginBottom:14}}>Einen Arbeitgeber gefunden, der noch nicht in der App ist? Melde ihn hier — nach Prüfung wird er aufgenommen.</div>

            {empSent&&<div style={{background:"#16653422",border:"1px solid #22C55E",borderRadius:10,padding:12,marginBottom:14,fontSize:13,color:"#22C55E",fontWeight:600}}>Danke! Dein Vorschlag wurde gesendet und wird geprüft.</div>}

            {(()=>{
              // Info-Icon-Komponente: kleines „i", Klick öffnet Hinweis-Box
              const Info=({id,text})=>(
                <button type="button" onClick={()=>setEmpInfoOpen(empInfoOpen===id?"":id)} title="Hinweis anzeigen"
                  style={{width:20,height:20,borderRadius:"50%",background:empInfoOpen===id?"#3B82F6":"#334155",border:"none",color:"white",fontSize:11,fontWeight:700,cursor:"pointer",fontFamily:"system-ui",display:"inline-flex",alignItems:"center",justifyContent:"center",marginLeft:6,verticalAlign:"middle",fontStyle:"italic"}}>i</button>
              );
              const Label=({id,text,info,required})=>(
                <>
                  <div style={{display:"flex",alignItems:"center",marginBottom:6}}>
                    <span style={{fontSize:12,color:"#64748B"}}>{text}{required?" *":""}</span>
                    {info?<Info id={id}/>:null}
                  </div>
                  {empInfoOpen===id&&info?<div style={{background:"#1E293B",border:"1px solid #3B82F6",borderRadius:8,padding:10,marginBottom:8,fontSize:12,color:"#CBD5E1",lineHeight:1.5,whiteSpace:"pre-line"}}>💡 {info}</div>:null}
                </>
              );
              return(<>
                <Label id="name" text="Firmenname" required info={`Offizieller Firmenname (z.B. „Globus SB-Warenhaus"). Bitte exakte Schreibweise wie auf der Webseite.`}/>
                <input value={empForm.name} onChange={e=>setEmpForm({...empForm,name:e.target.value})} placeholder="z.B. Globus, Deichmann..." style={{...II,marginBottom:12}}/>

                <Label id="branche" text="Branche" info={"Wähle die passende Kategorie. Wird für Filter und Statistiken in der App genutzt."}/>
                <div style={{display:"flex",gap:5,flexWrap:"wrap",marginBottom:12}}>
                  {BRANCHES.map(b=>(<button key={b} onClick={()=>setEmpForm({...empForm,branche:b})} style={chip(empForm.branche===b,"#3B82F6")}>{b}</button>))}
                </div>

                <Label id="vwl" text="VWL-Betrag (AG-Anteil)" info={"Wichtig — falls bekannt, bitte angeben:\n• Was zahlt der Arbeitgeber pro Monat? (z.B. 13,29 €)\n• Was gilt für Vollzeit-Mitarbeiter?\n• Was gilt für Azubis?\n• Ab welcher Betriebszugehörigkeit (z.B. ab 1 Jahr)?\n\nWenn unbekannt: Feld leer lassen."}/>
                <input value={empForm.vwl} onChange={e=>setEmpForm({...empForm,vwl:e.target.value})} placeholder="z.B. 13,29 € oder 'ab 1 Jahr'" style={{...II,marginBottom:12}}/>

                <Label id="address" text="Adresse / Standort" info={`Adresse einer konkreten Filiale. Falls mehrere Standorte: einen Beispielstandort angeben oder „Bundesweit" eintragen.`}/>
                <input value={empForm.address} onChange={e=>setEmpForm({...empForm,address:e.target.value})} placeholder="z.B. Hauptstraße 12, München" style={{...II,marginBottom:12}}/>

                <Label id="website" text="Internetseite mit offiziellem Beweis" required info={"Pflichtangabe! Link zu einer offiziellen Quelle, die den VWL-Anspruch belegt:\n• Tarifvertrag\n• Karriereseite des Arbeitgebers\n• Mitarbeiter-Benefits / Sozialleistungen\n• Pressemitteilung\n\nNur mit Beleg kann der Arbeitgeber aufgenommen werden."}/>
                <input value={empForm.website} onChange={e=>setEmpForm({...empForm,website:e.target.value})} placeholder="https://www.firma.de/karriere/leistungen" style={{...II,marginBottom:12}}/>

                <Label id="contact" text="Ansprechpartner" info={"Person, die den Tipp bestätigen oder Auskunft geben kann (z.B. Filialleiter, Personalabteilung)."}/>
                <input value={empForm.contact} onChange={e=>setEmpForm({...empForm,contact:e.target.value})} placeholder="z.B. Herr Schmidt, Filialleiter" style={{...II,marginBottom:12}}/>

                <Label id="notes" text="Anmerkungen (optional)" info={"Weitere Infos: Besonderheiten, ab wann VWL gezahlt wird, ob nur in bestimmten Regionen, etc."}/>
                <textarea value={empForm.notes} onChange={e=>setEmpForm({...empForm,notes:e.target.value})} placeholder="Weitere Infos zum Arbeitgeber..." rows={3} style={{...II,resize:"vertical",lineHeight:1.5,marginBottom:14}}/>
              </>);
            })()}

            {(()=>{const ok=empForm.name.trim()&&empForm.website.trim();return(
              <button onClick={submitEmployer} disabled={!ok} style={{width:"100%",padding:"14px",background:ok?"#3B82F6":"#334155",border:"none",borderRadius:12,color:"white",fontSize:15,fontWeight:700,cursor:ok?"pointer":"default",fontFamily:"inherit",opacity:ok?1:0.5}}>
                Arbeitgeber vorschlagen
              </button>
            )})()}
            {!empForm.website.trim()&&empForm.name.trim()&&<div style={{fontSize:11,color:"#F59E0B",marginTop:8,textAlign:"center"}}>Bitte Internetseite mit offiziellem Beweis ausfüllen.</div>}
          </div>

          {currentUser&&currentUser.role==="admin"&&<div style={{...CC,border:"1px solid #F59E0B"}}>
            <div style={{fontSize:16,fontWeight:700,color:"#F59E0B",marginBottom:12}}>Team-Dashboard</div>
            {teamStats.length===0?(
              <div style={{fontSize:13,color:"#64748B",padding:"8px 0"}}>Keine Daten verfügbar.</div>
            ):(
              <>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,marginBottom:14,textAlign:"center"}}>
                  <div style={{background:"#0F172A",borderRadius:8,padding:10}}>
                    <div style={{fontSize:22,fontWeight:700,color:"#60A5FA"}}>{teamStats.reduce((s,u)=>s+u.todayVisits,0)}</div>
                    <div style={{fontSize:10,color:"#94A3B8"}}>Heute</div>
                  </div>
                  <div style={{background:"#0F172A",borderRadius:8,padding:10}}>
                    <div style={{fontSize:22,fontWeight:700,color:"#3B82F6"}}>{teamStats.reduce((s,u)=>s+u.weekVisits,0)}</div>
                    <div style={{fontSize:10,color:"#94A3B8"}}>Woche</div>
                  </div>
                  <div style={{background:"#0F172A",borderRadius:8,padding:10}}>
                    <div style={{fontSize:22,fontWeight:700,color:"#22C55E"}}>{teamStats.reduce((s,u)=>s+u.totalContracts,0)}</div>
                    <div style={{fontSize:10,color:"#94A3B8"}}>Verträge ges.</div>
                  </div>
                </div>
                {[...teamStats].sort((a,b)=>b.weekVisits-a.weekVisits).map(u=>(
                  <div key={u.id} style={{display:"flex",alignItems:"center",gap:10,padding:"10px 0",borderBottom:"1px solid #334155"}}>
                    <div style={{width:36,height:36,borderRadius:"50%",background:u.role==="admin"?"#F59E0B22":"#3B82F622",border:u.role==="admin"?"1px solid #F59E0B":"1px solid #3B82F6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:700,flexShrink:0,color:u.role==="admin"?"#F59E0B":"#3B82F6"}}>{(u.name||"?")[0]}</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontWeight:600,fontSize:13}}>{u.name}</div>
                      <div style={{fontSize:11,color:"#64748B"}}>{u.region||"Keine Region"}{u.lastActive?` · Zuletzt: ${u.lastActive}`:""}</div>
                    </div>
                    <div style={{display:"flex",gap:10,textAlign:"center",flexShrink:0}}>
                      <div><div style={{fontSize:15,fontWeight:700,color:"#60A5FA"}}>{u.todayVisits}</div><div style={{fontSize:9,color:"#64748B"}}>Heute</div></div>
                      <div><div style={{fontSize:15,fontWeight:700,color:"#3B82F6"}}>{u.weekVisits}</div><div style={{fontSize:9,color:"#64748B"}}>Woche</div></div>
                      <div><div style={{fontSize:15,fontWeight:700,color:"#22C55E"}}>{u.totalContracts}</div><div style={{fontSize:9,color:"#64748B"}}>Verträge</div></div>
                    </div>
                  </div>
                ))}
              </>
            )}
          </div>}

          {currentUser&&currentUser.role==="admin"&&empSuggestions.length>0&&<div style={{...CC,border:"1px solid #F97316"}}>
            <div style={{fontSize:16,fontWeight:700,color:"#F97316",marginBottom:12}}>Arbeitgeber-Vorschläge ({empSuggestions.filter(s=>s.status==="pending").length} offen)</div>
            {empSuggestions.filter(s=>s.status==="pending").map(s=>(
              <div key={s.id} style={{background:"#0F172A",borderRadius:10,padding:12,marginBottom:8}}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:6}}>
                  <div>
                    <div style={{fontWeight:700,fontSize:14}}>{s.name}</div>
                    {s.branche&&<div style={{fontSize:12,color:"#94A3B8"}}>{s.branche}</div>}
                  </div>
                  <div style={{fontSize:10,color:"#64748B"}}>{s.createdAt?new Date(s.createdAt).toLocaleDateString("de-DE"):""}</div>
                </div>
                {s.vwl&&<div style={{fontSize:12,color:"#22C55E",marginBottom:2}}>VWL: {s.vwl}</div>}
                {s.address&&<div style={{fontSize:12,color:"#94A3B8",marginBottom:2}}>📍 {s.address}</div>}
                {s.contact&&<div style={{fontSize:12,color:"#60A5FA",marginBottom:2}}>👤 {s.contact}</div>}
                {s.notes&&<div style={{fontSize:12,color:"#64748B",marginBottom:6}}>{s.notes}</div>}
                <div style={{display:"flex",gap:6,marginTop:8}}>
                  <button onClick={async()=>{try{await fetch(`/api/employer-suggestions/${s.id}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({status:"approved"})});const r=await fetch('/api/employer-suggestions');setEmpSuggestions(await r.json())}catch{}}} style={{flex:1,padding:"8px",background:"#22C55E",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>Annehmen</button>
                  <button onClick={async()=>{try{await fetch(`/api/employer-suggestions/${s.id}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({status:"rejected"})});const r=await fetch('/api/employer-suggestions');setEmpSuggestions(await r.json())}catch{}}} style={{flex:1,padding:"8px",background:"#EF4444",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>Ablehnen</button>
                </div>
              </div>
            ))}
            {empSuggestions.filter(s=>s.status!=="pending").length>0&&<div style={{marginTop:8}}>
              <div style={{fontSize:12,color:"#64748B",marginBottom:6}}>Bearbeitet ({empSuggestions.filter(s=>s.status!=="pending").length})</div>
              {empSuggestions.filter(s=>s.status!=="pending").map(s=>(
                <div key={s.id} style={{display:"flex",alignItems:"center",gap:8,padding:"6px 0",borderBottom:"1px solid #1E293B",fontSize:12}}>
                  <span style={{color:s.status==="approved"?"#22C55E":"#EF4444",fontWeight:600}}>{s.status==="approved"?"✓":"✕"}</span>
                  <span style={{color:"#94A3B8",flex:1}}>{s.name}</span>
                  {s.branche&&<span style={{color:"#64748B"}}>{s.branche}</span>}
                </div>
              ))}
            </div>}
          </div>}

          {currentUser&&currentUser.role==="admin"&&(()=>{
            const allDocs=docs;
            const docTypes2=[{id:"antrag",icon:"📝",label:"Antrag"},{id:"gehalt",icon:"💰",label:"Gehaltsnachweis"},{id:"vollmacht",icon:"📋",label:"Vollmacht"},{id:"sonstiges",icon:"📎",label:"Sonstiges"}];
            const token=localStorage.getItem("authToken")||"";
            return <div style={{...CC,border:"1px solid #3B82F6"}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12}}>
                <div style={{fontSize:16,fontWeight:700,color:"#60A5FA"}}>📄 Dokumente-Verwaltung</div>
                <div style={{fontSize:12,color:"#64748B"}}>{allDocs.length} gesamt</div>
              </div>
              {allDocs.length===0?<div style={{fontSize:13,color:"#64748B"}}>Noch keine Dokumente hochgeladen</div>:
                allDocs.slice().reverse().map(d=>(
                  <div key={d.id} style={{background:"#0F172A",borderRadius:10,padding:12,marginBottom:8}}>
                    <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:8}}>
                      <span style={{fontSize:18}}>{docTypes2.find(t=>t.id===d.type)?.icon||"📄"}</span>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontWeight:600,fontSize:13}}>{d.storeName||"Unbekannt"}</div>
                        <div style={{fontSize:11,color:"#94A3B8"}}>{d.userName} · {new Date(d.createdAt).toLocaleDateString("de-DE",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}</div>
                      </div>
                      <button onClick={async()=>{if(!confirm("Dokument wirklich löschen?"))return;try{const r=await fetch("/api/docs/"+d.id,{method:"DELETE"});const j=await r.json();if(j.ok)setDocs(x=>x.filter(dd=>dd.id!==d.id))}catch{}}} style={{background:"#7F1D1D",border:"1px solid #EF4444",borderRadius:6,padding:"4px 8px",color:"#FCA5A5",fontSize:11,cursor:"pointer",fontFamily:"inherit"}}>Löschen</button>
                    </div>
                    <div style={{display:"flex",gap:6,overflowX:"auto",paddingBottom:4}}>
                      {(d.files||[]).map((f,i)=>(
                        <img key={i} src={"/api/docs/file/"+f+"?token="+token} onClick={()=>window.open("/api/docs/file/"+f+"?token="+token,"_blank")} style={{width:60,height:60,objectFit:"cover",borderRadius:8,border:"1px solid #334155",cursor:"pointer",flexShrink:0}}/>
                      ))}
                    </div>
                    {d.note&&<div style={{fontSize:11,color:"#64748B",marginTop:6}}>{d.note}</div>}
                  </div>
                ))
              }
            </div>;
          })()}

          {currentUser&&currentUser.role==="admin"&&<div style={{...CC,border:"1px solid #7C3AED"}}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12}}>
              <div style={{fontSize:16,fontWeight:700,color:"#C4B5FD"}}>Nutzerverwaltung</div>
              <button onClick={()=>setShowAddUser(!showAddUser)} style={{padding:"6px 14px",background:showAddUser?"#EF4444":"#7C3AED",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>{showAddUser?"✕":"+ Nutzer"}</button>
            </div>
            {showAddUser&&<div style={{background:"#0F172A",borderRadius:10,padding:14,marginBottom:14}}>
              <div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Name *</div>
              <input value={newUser.name} onChange={e=>setNewUser({...newUser,name:e.target.value})} placeholder="Vor- und Nachname" style={{...II,marginBottom:10}}/>
              <div style={{fontSize:12,color:"#64748B",marginBottom:4}}>PIN * (4-6 Ziffern)</div>
              <input value={newUser.pin} onChange={e=>setNewUser({...newUser,pin:e.target.value.replace(/[^0-9]/g,"")})} maxLength={6} placeholder="z.B. 5678" style={{...II,marginBottom:10}}/>
              <div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Rolle</div>
              <div style={{display:"flex",gap:6,marginBottom:10}}>
                <button onClick={()=>setNewUser({...newUser,role:"partner"})} style={chip(newUser.role==="partner","#3B82F6")}>Partner</button>
                <button onClick={()=>setNewUser({...newUser,role:"admin"})} style={chip(newUser.role==="admin","#F59E0B")}>Admin</button>
              </div>
              <div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Region</div>
              <input value={newUser.region} onChange={e=>setNewUser({...newUser,region:e.target.value})} placeholder="z.B. München" style={{...II,marginBottom:10}}/>
              <div style={{fontSize:12,color:"#64748B",marginBottom:4}}>Telefon</div>
              <input value={newUser.phone} onChange={e=>setNewUser({...newUser,phone:e.target.value})} placeholder="z.B. 0170 1234567" style={{...II,marginBottom:10}}/>
              <div style={{fontSize:12,color:"#64748B",marginBottom:4}}>E-Mail</div>
              <input value={newUser.email} onChange={e=>setNewUser({...newUser,email:e.target.value})} placeholder="z.B. max@beispiel.de" style={{...II,marginBottom:10}}/>
              <button onClick={createUser} disabled={!newUser.name.trim()||!newUser.pin.trim()} style={{width:"100%",padding:"12px",background:newUser.name.trim()&&newUser.pin.trim()?"#7C3AED":"#334155",border:"none",borderRadius:10,color:"white",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit",opacity:newUser.name.trim()&&newUser.pin.trim()?1:0.5}}>Nutzer anlegen</button>
            </div>}
            {adminUsers.length>0?adminUsers.map(u=>(<div key={u.id} style={{padding:"10px 0",borderBottom:"1px solid #334155"}}>
              <div style={{display:"flex",alignItems:"center",gap:10}}>
                <div style={{width:36,height:36,borderRadius:"50%",background:u.role==="admin"?"#F59E0B22":"#3B82F622",border:u.role==="admin"?"1px solid #F59E0B":"1px solid #3B82F6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,flexShrink:0}}>{u.role==="admin"?"👑":"👤"}</div>
                <div style={{flex:1}}><div style={{fontWeight:600,fontSize:13}}>{u.name}</div><div style={{fontSize:11,color:"#64748B"}}>{u.role==="admin"?"Admin":"Partner"}{u.region?` · ${u.region}`:""}</div></div>
                <button onClick={()=>toggleUserActive(u.id,u.active!==false)} style={{padding:"4px 8px",borderRadius:6,border:"none",fontSize:10,fontWeight:600,cursor:"pointer",fontFamily:"inherit",background:u.active!==false?"#22C55E22":"#EF444422",color:u.active!==false?"#22C55E":"#EF4444"}}>{u.active!==false?"Aktiv":"Inaktiv"}</button>
                <button onClick={()=>{setEditUserId(editUserId===u.id?null:u.id);setEditUserPin("")}} style={{padding:"4px 8px",borderRadius:6,border:"none",fontSize:10,fontWeight:600,cursor:"pointer",fontFamily:"inherit",background:"#334155",color:"#E2E8F0"}}>PIN</button>
              </div>
              {editUserId===u.id&&<div style={{display:"flex",gap:6,marginTop:8,marginLeft:46}}>
                <input value={editUserPin} onChange={e=>setEditUserPin(e.target.value.replace(/[^0-9]/g,""))} type="password" inputMode="numeric" maxLength={6} placeholder="Neuer PIN" style={{...II,flex:1,padding:"8px 10px",fontSize:13}}/>
                <button onClick={()=>updateUserPin(u.id)} disabled={!editUserPin.trim()} style={{padding:"8px 14px",background:editUserPin.trim()?"#7C3AED":"#334155",border:"none",borderRadius:8,color:"white",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",opacity:editUserPin.trim()?1:0.5}}>Ändern</button>
              </div>}
            </div>)):<div style={{fontSize:13,color:"#64748B",padding:"8px 0"}}>Keine Nutzer angelegt.</div>}
          </div>}

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{fontSize:16,fontWeight:700,marginBottom:12}}>Datenschutz</div>
            <div style={{fontSize:13,color:"#94A3B8",marginBottom:10}}>
              {privacyDate?`Zugestimmt am ${new Date(privacyDate).toLocaleDateString("de-DE",{day:"numeric",month:"long",year:"numeric"})} um ${new Date(privacyDate).toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})} Uhr`:"Nicht bestätigt"}
            </div>
            <button onClick={()=>{localStorage.removeItem("privacyAccepted");setPrivacyAccepted(false)}} style={{padding:"10px 16px",background:"#334155",border:"none",borderRadius:10,color:"#E2E8F0",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"inherit",marginRight:8}}>
              Datenschutzerklärung erneut anzeigen
            </button>
          </div>

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{fontSize:16,fontWeight:700,marginBottom:12}}>App-Info</div>
            <div style={{display:"flex",flexDirection:"column",gap:8,fontSize:13,color:"#94A3B8"}}>
              <div style={{display:"flex",justifyContent:"space-between"}}><span>Version</span><span style={{color:"#E2E8F0",fontWeight:600}}>1.2.0</span></div>
              <div style={{display:"flex",justifyContent:"space-between"}}><span>Filialen geladen</span><span style={{color:"#E2E8F0",fontWeight:600}}>{allStores.length>0?allStores.length:stores.length}</span></div>
              <div style={{display:"flex",justifyContent:"space-between"}}><span>GPS</span><span style={{color:gpsStatus==="active"?"#22C55E":"#F59E0B",fontWeight:600}}>{gpsStatus==="active"?"Aktiv":gpsStatus==="off"?"Deaktiviert":"Warte..."}</span></div>
              <div style={{display:"flex",justifyContent:"space-between"}}><span>Daten-Cache</span><span style={{color:"#E2E8F0",fontWeight:600}}>{localStorage.getItem("allStores")?"Aktiv":"—"}</span></div>
            </div>
          </div>

          <div style={{...CC,border:"1px solid #334155"}}>
            <div style={{fontSize:16,fontWeight:700,marginBottom:12}}>Daten</div>
            <div style={{display:"flex",gap:8}}>
              <button onClick={()=>window.open('/api/backup?token='+(localStorage.getItem('authToken')||''),'_blank')} style={{flex:1,padding:"12px",background:"#334155",border:"none",borderRadius:10,color:"#E2E8F0",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>
                Backup herunterladen
              </button>
              <button onClick={()=>{if(confirm("Cache leeren? Filialen werden beim nächsten Laden neu geladen.")){localStorage.removeItem("allStores");localStorage.removeItem("allStoresTime");location.reload()}}} style={{flex:1,padding:"12px",background:"#334155",border:"none",borderRadius:10,color:"#F59E0B",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>
                Cache leeren
              </button>
            </div>
          </div>

          <button onClick={logout} style={{width:"100%",padding:"14px",background:"#1E293B",border:"1px solid #EF4444",borderRadius:12,color:"#EF4444",fontSize:15,fontWeight:700,cursor:"pointer",fontFamily:"inherit",marginBottom:16}}>
            Abmelden
          </button>

        </div>
      </div>
    );
  }

  // ══════ LIST ══════
  const onPullStart=e=>{if(window.scrollY<=0){pullRef.current={startY:e.touches[0].clientY,active:true}}};
  const onPullMove=e=>{if(!pullRef.current.active)return;const dy=e.touches[0].clientY-pullRef.current.startY;if(dy>0&&dy<120)setPullY(dy)};
  const onPullEnd=()=>{if(pullY>60&&!refreshing){setRefreshing(true);haptic(15);const loc=planLoc||userLoc;fetch(`/api/stores?lat=${loc.lat}&lng=${loc.lng}&radius=${radius}`).then(r=>r.json()).then(d=>{if(d.length>0)setStores(d);setRefreshing(false);setPullY(0)}).catch(()=>{setRefreshing(false);setPullY(0)})}else{setPullY(0)}pullRef.current.active=false};
  if(!pageContent) pageContent=(
    <div style={Z} onTouchStart={onPullStart} onTouchMove={onPullMove} onTouchEnd={onPullEnd}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"/>
      {(pullY>10||refreshing)&&<div style={{textAlign:"center",padding:"8px 0",color:"#3B82F6",fontSize:12,fontWeight:600,transition:"all 0.2s"}}>{refreshing?"Aktualisiere...":"↓ Loslassen zum Aktualisieren"}</div>}
      <div style={{padding:"16px 20px 0",background:"linear-gradient(180deg,#1E293B 0%,#0F172A 100%)"}}>
        <div style={{display:"flex",alignItems:"center",gap:12}}>
          <button onClick={()=>setPage("home")} style={BB}>←</button>
          <div style={{flex:1,fontSize:17,fontWeight:700}}>📋 Filialen</div>
          <div style={{display:"flex",alignItems:"center",gap:8}}>
            <div style={{background:"#1E293B",borderRadius:8,padding:"4px 10px",display:"flex",alignItems:"center",gap:4,border:"1px solid #334155"}}>
              <span style={{fontSize:14}}>{lvl.icon}</span>
              <span style={{fontSize:11,fontWeight:700,color:"#C4B5FD"}}>{xp} XP</span>
            </div>
            <GpsToggle/>
          </div>
        </div>
        <div style={{background:"#0F172A",borderRadius:10,padding:12,marginTop:10,border:"1px solid #334155"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
            <div style={{fontSize:13,fontWeight:700}}>Heute, {new Date().toLocaleDateString("de-DE",{day:"numeric",month:"short"})}</div>
            {gStreak>0&&<div style={{fontSize:12,color:"#F97316",fontWeight:700}}>{gStreak}🔥 Streak</div>}
          </div>
          {todayV===0?(
            <div style={{fontSize:13,color:"#64748B"}}>Noch keine Besuche — leg los! 💪</div>
          ):(
            <div style={{display:"flex",gap:16}}>
              <div style={{textAlign:"center"}}><div style={{fontSize:20,fontWeight:700,color:"#60A5FA"}}>{todayV}</div><div style={{fontSize:10,color:"#94A3B8"}}>Besuche</div></div>
              <div style={{textAlign:"center"}}><div style={{fontSize:20,fontWeight:700,color:"#3B82F6"}}>{todayD}</div><div style={{fontSize:10,color:"#94A3B8"}}>Rein</div></div>
              <div style={{textAlign:"center"}}><div style={{fontSize:20,fontWeight:700,color:"#22C55E"}}>{todayG}</div><div style={{fontSize:10,color:"#94A3B8"}}>Geschrieben</div></div>
            </div>
          )}
        </div>
        <div style={{fontSize:12,color:"#64748B",marginTop:8}}>{storesLoading?"Lade Filialen...":planLoc?`📍 Planung: ${planLoc.name} · ${fl.length} Filialen`:`${fl.length} Filialen im Umkreis von ${radius} km`}</div>
        {planLoc&&<button onClick={()=>setPlanLoc(null)} style={{marginTop:6,padding:"5px 12px",background:"#7C3AED22",border:"1px solid #7C3AED",borderRadius:8,color:"#C4B5FD",fontSize:11,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}}>✕ Planung beenden → GPS</button>}
        <div style={{display:"flex",gap:6,marginTop:10,paddingBottom:14}}>
          {[{l:"Gesamt",v:st2.total,c:"#60A5FA"},{l:"🔥",v:st2.besuchbar,c:"#F97316"},{l:"🤩",v:st2.drin||0,c:"#3B82F6"},{l:"💸",v:st2.geschrieben||0,c:"#22C55E"},{l:"❌",v:st2.abgelehnt||0,c:"#EF4444"}].map(x=>(
            <div key={x.l} style={{flex:1,background:"#0F172A",borderRadius:8,padding:"8px 4px",textAlign:"center",border:"1px solid #1E293B"}}>
              <div style={{fontSize:18,fontWeight:700,color:x.c}}>{x.v}</div>
              <div style={{fontSize:10,color:"#64748B"}}>{x.l}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{padding:"10px 20px",position:"sticky",top:0,background:"#0F172A",zIndex:10,borderBottom:"1px solid #1E293B"}}>
        <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="🔍 Suchen..." style={{...II,background:"#1E293B",borderRadius:12,padding:"11px 14px"}}/>
        <div style={{display:"flex",gap:5,marginTop:8,overflowX:"auto",paddingBottom:2}}>
          <button onClick={()=>setFCat("all")} style={chip(fCat==="all","#3B82F6")}>Alle</button>
          {Object.entries(CATS).map(([k,c])=>(<button key={k} onClick={()=>setFCat(k)} style={chip(fCat===k,c.color)}>{c.icon}</button>))}
        </div>
        <div style={{display:"flex",gap:5,marginTop:6,overflowX:"auto",paddingBottom:2}}>
          {[{l:"5 km",v:5},{l:"10 km",v:10},{l:"25 km",v:25},{l:"50 km",v:50},{l:"100 km",v:100}].map(r=>(
            <button key={r.v} onClick={()=>setRadius(r.v)} style={chip(radius===r.v,"#8B5CF6")}>📍 {r.l}</button>
          ))}
        </div>
      </div>
      <div style={{padding:"8px 20px 80px"}}>
        {fl.length===0?<div style={{textAlign:"center",padding:40,color:"#64748B"}}><div style={{fontSize:36}}>🔍</div><div style={{marginTop:8}}>Keine Ergebnisse</div></div>
        :fl.map(store=>{
          const cat=getCat(store.id),ci=CATS[cat]||CATS.besuchbar,d=getData(store.id),vs=d.visits||[];
          const swRef={sX:null,sY:null};
          const onSS=e=>{const t=e.touches[0];swRef.sX=t.clientX;swRef.sY=t.clientY};
          const onSE=e=>{if(swRef.sX===null)return;const t=e.changedTouches[0];const dx=t.clientX-swRef.sX;const dy=Math.abs(t.clientY-swRef.sY);swRef.sX=null;if(Math.abs(dx)>70&&dy<40){if(dx>0){haptic(15);setTour(tt=>tt.some(x=>x.id===store.id)?tt:[...tt,store]);setSaveMsg("🧭 Zur Tour hinzugefügt");if(stRef.current)clearTimeout(stRef.current);stRef.current=setTimeout(()=>setSaveMsg(""),1500)}else{haptic(15);nav(store)}}};
          return(
            <div key={store.id} onClick={()=>{setSel(store);setPage("detail");setEditNote(false);setShowAV(false)}}
              onTouchStart={onSS} onTouchEnd={onSE}
              style={{background:"#1E293B",borderRadius:12,padding:13,marginBottom:8,cursor:"pointer",borderLeft:`4px solid ${ci.color}`}}>
              <div style={{display:"flex",gap:11,alignItems:"flex-start"}}>
                <div style={{position:"relative",flexShrink:0}}>
                  <Logo employer={store.employer} size={42}/>
                  <span style={{position:"absolute",bottom:-2,right:-2,width:10,height:10,borderRadius:"50%",background:ci.color,border:"2px solid #1E293B"}}></span>
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontWeight:700,fontSize:14}}>{store.name}</div>
                  <div style={{fontSize:12,color:"#94A3B8",marginTop:2}}>{store.address}</div>
                  {d.contact&&<div style={{fontSize:11,color:"#60A5FA",marginTop:3}}>👤 {d.contact}{d.personType?` · ${d.personType}`:""}</div>}
                  {vs.length>0&&<div style={{fontSize:11,color:"#64748B",marginTop:2}}>📋 {vs.length} Besuch{vs.length>1?"e":""} · {d.lastVisit}</div>}
                  {d.notes&&<div style={{fontSize:11,color:"#475569",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>📝 {d.notes}</div>}
                </div>
                <div style={{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:3,flexShrink:0}}>
                  <div style={{fontSize:12,color:"#60A5FA",fontWeight:700,background:"#1E3A5F",padding:"2px 8px",borderRadius:10,whiteSpace:"nowrap"}}>📍 {distStr(store)}</div>
                  <div style={{fontSize:11,color:"#22C55E",fontWeight:600}}>{store.vwl}</div>
                  <div style={{fontSize:10,color:"#94A3B8",whiteSpace:"nowrap"}}>{store.branch}</div>
                  <div style={{display:"flex",gap:4}}>
                    <button onClick={e=>{e.stopPropagation();setTour(t=>t.some(x=>x.id===store.id)?t:[...t,store])}} style={{padding:"4px 8px",background:tour.some(x=>x.id===store.id)?"#7C3AED22":"#334155",border:tour.some(x=>x.id===store.id)?"1px solid #7C3AED":"none",borderRadius:6,color:tour.some(x=>x.id===store.id)?"#7C3AED":"#C4B5FD",fontSize:11,cursor:"pointer",fontFamily:"inherit"}}>{tour.some(x=>x.id===store.id)?"✓":"+"}</button>
                    <button onClick={e=>{e.stopPropagation();nav(store)}} style={{padding:"4px 8px",background:"#334155",border:"none",borderRadius:6,color:"#60A5FA",fontSize:11,cursor:"pointer"}}>🧭</button>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );

  // ═══ FEEDBACK-AVATAR ═══
  const fbCategories = [
    { id: "bug", icon: "🐛", label: "Fehler melden", desc: "Etwas funktioniert nicht richtig" },
    { id: "idea", icon: "💡", label: "Verbesserung", desc: "Ich habe eine Idee" },
    { id: "frage", icon: "❓", label: "Frage stellen", desc: "Ich brauche Hilfe" },
    { id: "lob", icon: "⭐", label: "Lob & Feedback", desc: "Das gefällt mir gut" },
  ];

  const fbReset = () => { setFbStep("menu"); setFbCat(""); setFbMsg(""); setFbSent(false); setFbLoading(false); setFbError(false); };
  const handleUpload = async () => { if (!uploadFile || !sel) return; setUploading(true); try { const formData = new FormData(); formData.append("file", uploadFile); formData.append("storeId", sel.id); formData.append("category", uploadCategory); const r = await fetch("/api/uploads", {method: "POST", body: formData}); if (!r.ok) { setUploading(false); alert("Upload fehlgeschlagen"); return; } setUploading(false); setUploadModal(false); setUploadFile(null); setSaveMsg("Upload erfolgreich!"); setTimeout(() => setSaveMsg(""), 3000); } catch (e) { setUploading(false); alert("Fehler: " + e.message); } };
  const fbSend = async () => {
    if (!fbMsg.trim() || fbLoading) return;
    setFbLoading(true); setFbError(false);
    try {
      const r = await fetch("/api/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user: currentUser?.name || "Anonym", category: fbCat, message: fbMsg.trim() }) });
      if (!r.ok) throw new Error();
      setFbSent(true); setFbLoading(false);
      setTimeout(() => { setFbOpen(false); fbReset(); }, 2800);
    } catch { setFbLoading(false); setFbError(true); }
  };

  return(
    <>
      {pageContent}
      <Sv/>

      {/* Feedback Overlay */}
      {fbOpen && <div onClick={() => { setFbOpen(false); fbReset(); }} style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, background: "rgba(0,0,0,0.4)", zIndex: 90, WebkitBackfaceVisibility: "hidden" }} />}

      {/* Feedback Panel */}
      {fbOpen && (
        <div style={{
          position: "fixed", bottom: 90, left: 16, width: 320, maxWidth: "calc(100vw - 32px)",
          background: "#1E293B", borderRadius: 16, zIndex: 91, overflow: "hidden",
          boxShadow: "0 12px 40px rgba(0,0,0,0.5)", border: "1px solid #334155",
          WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)",
        }}>
          <div style={{ background: "linear-gradient(135deg, #3B82F6, #7C3AED)", padding: "16px 18px", display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20 }}>💬</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 14, color: "white" }}>Feedback & Ideen</div>
              <div style={{ fontSize: 11, color: "rgba(255,255,255,0.7)" }}>Hilf uns die App zu verbessern</div>
            </div>
            <button onClick={() => { setFbOpen(false); fbReset(); }} style={{ background: "rgba(255,255,255,0.2)", border: "none", borderRadius: 8, width: 28, height: 28, color: "white", fontSize: 14, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>✕</button>
          </div>
          <div style={{ padding: 16, maxHeight: 340, overflowY: "auto" }}>
            {fbSent ? (
              <div style={{ textAlign: "center", padding: "30px 0" }}>
                <div style={{ fontSize: 48, marginBottom: 10, animation: "fbPop 0.3s ease-out" }}>🎉</div>
                <div style={{ fontWeight: 700, fontSize: 16, color: "#E2E8F0" }}>Danke für dein Feedback!</div>
                <div style={{ fontSize: 13, color: "#94A3B8", marginTop: 6 }}>Wir schauen uns das an.</div>
              </div>
            ) : fbStep === "menu" ? (
              <>
                <div style={{ fontSize: 13, color: "#94A3B8", marginBottom: 12 }}>Was möchtest du uns mitteilen?</div>
                {fbCategories.map(c => (
                  <button key={c.id} onClick={() => { setFbCat(c.id); setFbStep("write"); }}
                    style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", background: "#0F172A", border: "1px solid #334155", borderRadius: 10, marginBottom: 8, cursor: "pointer", textAlign: "left", transition: "border-color 0.15s" }}
                    onMouseEnter={e => e.currentTarget.style.borderColor = "#3B82F6"}
                    onMouseLeave={e => e.currentTarget.style.borderColor = "#334155"}>
                    <span style={{ fontSize: 22 }}>{c.icon}</span>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13, color: "#E2E8F0" }}>{c.label}</div>
                      <div style={{ fontSize: 11, color: "#64748B" }}>{c.desc}</div>
                    </div>
                  </button>
                ))}
              </>
            ) : (
              <>
                <button onClick={() => setFbStep("menu")} style={{ background: "none", border: "none", color: "#3B82F6", fontSize: 12, cursor: "pointer", marginBottom: 10, padding: 0, fontFamily: "inherit" }}>← Zurück</button>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, background: "#0F172A", padding: "8px 12px", borderRadius: 8 }}>
                  <span style={{ fontSize: 18 }}>{fbCategories.find(c => c.id === fbCat)?.icon}</span>
                  <span style={{ fontWeight: 600, fontSize: 13, color: "#E2E8F0" }}>{fbCategories.find(c => c.id === fbCat)?.label}</span>
                </div>
                <textarea value={fbMsg} onChange={e => setFbMsg(e.target.value.slice(0, 1000))} placeholder="Beschreibe es hier..." rows={4}
                  style={{ width: "100%", padding: "10px 12px", background: "#0F172A", border: "1px solid #334155", borderRadius: 8, color: "#E2E8F0", fontSize: 13, fontFamily: "inherit", resize: "none", boxSizing: "border-box" }}
                  autoFocus />
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
                  <span style={{ fontSize: 11, color: fbError ? "#EF4444" : "transparent" }}>{fbError ? "Senden fehlgeschlagen – bitte nochmal versuchen" : "."}</span>
                  <span style={{ fontSize: 11, color: fbMsg.length > 900 ? "#F59E0B" : "#64748B" }}>{fbMsg.length}/1000</span>
                </div>
                <button onClick={fbSend} disabled={!fbMsg.trim() || fbLoading}
                  style={{ width: "100%", marginTop: 8, padding: "11px", background: (!fbMsg.trim() || fbLoading) ? "#334155" : "linear-gradient(135deg, #3B82F6, #7C3AED)", border: "none", borderRadius: 10, color: "white", fontSize: 14, fontWeight: 600, cursor: (!fbMsg.trim() || fbLoading) ? "default" : "pointer", fontFamily: "inherit", opacity: fbLoading ? 0.7 : 1, transition: "opacity 0.15s" }}>
                  {fbLoading ? "Wird gesendet..." : "Absenden"}
                </button>
              </>
            )}
          </div>
        </div>
      )}

      {/* Feedback Floating Button */}
      <button onClick={() => { setFbOpen(!fbOpen); if (fbOpen) fbReset(); }}
        style={{
          position: "fixed", bottom: 76, left: 16, width: 52, height: 52,
          borderRadius: "50%", border: "none", cursor: "pointer", zIndex: 91,
          background: fbOpen ? "#EF4444" : "linear-gradient(135deg, #3B82F6, #7C3AED)",
          boxShadow: "0 4px 16px rgba(59,130,246,0.4)",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 24, color: "white",
          WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)",
        }}>
        {fbOpen ? "✕" : "💬"}
      </button>

      <BN/>
    </>
  );
}
