/* global React */
const { useState: useStateAD, useEffect: useEffectAD, useMemo: useMemoAD, useRef: useRefAD } = React;

/* =========================================================
   Storage — separate stores for Users and Companies, keyed
   by EMAIL (unique). All edits flow through email-based
   helpers so list order / search never desync.
   ========================================================= */
const USERS_KEY     = "aur.users.v1";
const COMPANIES_KEY = "aur.companies.v1";

function genTrend(seed) {
  const out = []; let v = 50;
  for (let i = 0; i < 12; i++) { v += Math.sin(seed + i * 0.7) * 8 + (i % 3 - 1) * 3; out.push(Math.max(10, Math.min(90, v))); }
  return out;
}

const SEED_COMPANIES = [
  { email: "ir@sap.com",        name: "SAP SE",                 symbol: "SAP",  totalShares: 10000, sharePrice: 214.60, buyPrice: 188.40, trend: genTrend(1.1), address: "Dietmar-Hopp-Allee 16, Walldorf", phone: "+49 6227 747474", contact: "Investor Relations", status: "verified", aum: 4280000 },
  { email: "ir@siemens.com",    name: "Siemens AG",             symbol: "SIE",  totalShares:  4500, sharePrice: 182.34, buyPrice: 165.10, trend: genTrend(2.3), address: "Werner-von-Siemens-Str. 1, München", phone: "+49 89 63600", contact: "Investor Relations", status: "verified", aum: 8120000 },
  { email: "ir@allianz.com",    name: "Allianz SE",             symbol: "ALV",  totalShares:  2600, sharePrice: 292.10, buyPrice: 271.80, trend: genTrend(3.4), address: "Königinstraße 28, München", phone: "+49 89 38000", contact: "Investor Relations", status: "verified", aum: 21700000 },
  { email: "ir@telekom.de",     name: "Deutsche Telekom AG",    symbol: "DTE",  totalShares: 18000, sharePrice:  24.85, buyPrice:  22.40, trend: genTrend(4.2), address: "Friedrich-Ebert-Allee 140, Bonn", phone: "+49 228 1810", contact: "Investor Relations", status: "verified", aum: 5400000 },
  { email: "ir@munichre.com",   name: "Münchener Rück AG",      symbol: "MUV2", totalShares:  1200, sharePrice: 486.70, buyPrice: 442.00, trend: genTrend(5.7), address: "Königinstraße 107, München", phone: "+49 89 38910", contact: "Investor Relations", status: "verified", aum: 9600000 },
  { email: "ir@basf.com",       name: "BASF SE",                symbol: "BAS",  totalShares:  8000, sharePrice:  45.92, buyPrice:  51.30, trend: genTrend(6.1), address: "Carl-Bosch-Str. 38, Ludwigshafen", phone: "+49 621 600", contact: "Investor Relations", status: "pending",  aum: 3100000 },
  { email: "ir@bmwgroup.com",   name: "BMW AG",                 symbol: "BMW",  totalShares:  5000, sharePrice:  78.44, buyPrice:  71.90, trend: genTrend(7.3), address: "Petuelring 130, München", phone: "+49 89 3820", contact: "Investor Relations", status: "verified", aum: 6200000 },
  { email: "ir@adidas.com",     name: "adidas AG",              symbol: "ADS",  totalShares:  2400, sharePrice: 228.30, buyPrice: 241.00, trend: genTrend(8.4), address: "Adi-Dassler-Str. 1, Herzogenaurach", phone: "+49 9132 840", contact: "Investor Relations", status: "pending",  aum: 4700000 },
  { email: "ir@infineon.com",   name: "Infineon Technologies AG", symbol: "IFX", totalShares: 14000, sharePrice:  31.28, buyPrice:  27.60, trend: genTrend(9.6), address: "Am Campeon 1-15, Neubiberg", phone: "+49 89 2340", contact: "Investor Relations", status: "verified", aum: 7800000 },
  { email: "ir@rwe.com",        name: "RWE AG",                 symbol: "RWE",  totalShares:  9000, sharePrice:  32.76, buyPrice:  35.90, trend: genTrend(10.8), address: "RWE-Platz 1, Essen", phone: "+49 201 51790", contact: "Investor Relations", status: "verified", aum: 3900000 },
];

const SEED_USERS = [
  { email: "j.diehl@example.de",     name: "Jonas Diehl",    address: "Königstraße 41, 70173 Stuttgart", phone: "+49 711 555 0123", status: "verified", companies: ["ir@sap.com", "ir@siemens.com"], role: "Owner", currency: "EUR", advisor: "Matthias Vollmer", advisorDesk: "Stuttgart · Königstraße 41", purchases: [{ id: "lot-sap-seed", companyEmail: "ir@sap.com", qty: 250, buyPrice: 188.4, buyDate: "2025-01-01", payment: "paid", lockUntil: "2027-01-01", note: "Verkaufssperre bis 01.01.2027 (Haltefrist)." }, { id: "lot-sie-seed", companyEmail: "ir@siemens.com", qty: 120, buyPrice: 165.1, buyDate: "2025-03-14", payment: "pending" }] },
  { email: "m.brandt@example.de",    name: "Miriam Brandt",  address: "Leopoldstraße 12, 80802 München", phone: "+49 89 555 0177",  status: "verified", companies: ["ir@allianz.com"], role: "Member", currency: "EUR", advisor: "Sebastian Kolb" },
  { email: "t.oezdemir@example.de",  name: "Tarek Özdemir",  address: "Hohe Straße 62, 50667 Köln",     phone: "+49 221 555 0112", status: "pending",  companies: ["ir@telekom.de"], role: "Member", currency: "EUR", advisor: "Aylin Demir" },
  { email: "s.wagner@example.de",    name: "Sophie Wagner",  address: "Mönckebergstraße 7, 20095 Hamburg", phone: "+49 40 555 0198", status: "verified", companies: ["ir@infineon.com", "ir@bmwgroup.com"], role: "Member", currency: "EUR", advisor: "Dr. Martin Eisele" },
];

/* One-time demo seed: gives the demo client a paid SAP lot (01.01.2025) and a Stuttgart broker. */
function ensureDemoSeed(users) {
  const FLAG = "aur.seed.v2";
  let done = false;
  try { done = localStorage.getItem(FLAG) === "1"; } catch (_) {}
  if (done) return users;
  try { localStorage.setItem(FLAG, "1"); } catch (_) {}
  return users.map(u => {
    if (u.email.toLowerCase() !== "j.diehl@example.de") return u;
    const lots = getUserLots(u);
    const hasSap = lots.some(l => l.id === "lot-sap-seed");
    if (hasSap) return u;
    const clean = lots.filter(l => l.companyEmail !== "ir@sap.com" && l.companyEmail !== "ir@siemens.com");
    const seeded = [
      { id: "lot-sap-seed", companyEmail: "ir@sap.com", qty: 250, buyPrice: 188.4, buyDate: "2025-01-01", payment: "paid" },
      { id: "lot-sie-seed", companyEmail: "ir@siemens.com", qty: 120, buyPrice: 165.1, buyDate: "2025-03-14", payment: "pending" },
    ];
    const next = withLots({ ...u, advisor: u.advisor || "Matthias Vollmer", advisorDesk: u.advisorDesk || "Stuttgart · Königstraße 41" }, [...seeded, ...clean]);
    return next;
  });
}

/* One-time patch: adds the sale lock/note to the seeded SAP lot (also on already-seeded storage). */
function ensureLockSeed(users) {
  // Idempotent: patches the demo SAP lot whenever its lock/note is missing,
  // independent of any flag, so stale browser storage also heals on load.
  let changed = false;
  const next = users.map(u => {
    if (u.email.toLowerCase() !== "j.diehl@example.de") return u;
    const lots = getUserLots(u);
    if (!lots.some(l => l.id === "lot-sap-seed")) return u;
    const patched = lots.map(l => {
      if (l.id !== "lot-sap-seed") return l;
      const lockUntil = l.lockUntil || "2027-01-01";
      const note = l.note || "Verkaufssperre bis 01.01.2027 (Haltefrist).";
      if (lockUntil === l.lockUntil && note === l.note) return l;
      changed = true;
      return { ...l, lockUntil, note };
    });
    return changed ? withLots(u, patched) : u;
  });
  if (changed) {
    try { localStorage.setItem("aur.seed.v3", "1"); } catch (_) {}
    return next;
  }
  return users;
}

function loadStore(key, seed) {
  try {
    const raw = localStorage.getItem(key);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (Array.isArray(parsed)) return key === USERS_KEY ? ensureLockSeed(ensureDemoSeed(parsed)) : parsed;
    }
  } catch (_) {}
  return key === USERS_KEY ? ensureLockSeed(ensureDemoSeed(seed)) : seed;
}
function saveStore(key, arr) { try { localStorage.setItem(key, JSON.stringify(arr)); } catch (_) {} }

const STATUS_OPTIONS = [
  { value: "verified", labelDe: "Verifiziert", labelEn: "Verified", color: "#34d399" },
  { value: "pending",  labelDe: "In Prüfung",  labelEn: "Pending",  color: "#fbbf24" },
  { value: "frozen",   labelDe: "Gesperrt",    labelEn: "Frozen",   color: "#f87171" },
];
function statusLabel(s, lang) { return lang === "de" ? s.labelDe : s.labelEn; }
function statusMeta(v, lang) {
  const s = STATUS_OPTIONS.find(x => x.value === v) || STATUS_OPTIONS[0];
  return { ...s, label: statusLabel(s, lang) };
}

/* Lots model: each user has u.purchases = [{ id, companyEmail, qty, buyPrice, buyDate, payment }]. */
function getUserLots(u) {
  if (Array.isArray(u.purchases) && u.purchases.length) return u.purchases;
  const list = Array.isArray(u.companies) ? u.companies : (u.company ? [u.company] : []);
  return list.map(cEmail => ({
    id: "lg-" + cEmail,
    companyEmail: cEmail,
    qty: (u.holdings && u.holdings[cEmail] != null) ? u.holdings[cEmail] : null,
    buyPrice: null,
    buyDate: null,
    payment: "pending",
  }));
}
function withLots(u, lots) {
  const companies = Array.from(new Set(lots.map(l => l.companyEmail)));
  return { ...u, purchases: lots, companies, company: companies[0] || "" };
}
function newLotId() { return "lot-" + Math.random().toString(36).slice(2, 9) + Date.now().toString(36); }

/* =========================================================
   AdminApp — top-level shell with internal routing
   ========================================================= */
function AdminApp({ lang, onLogout }) {
  const [page, setPage] = useStateAD(() => localStorage.getItem("aur.admin.page") || new URLSearchParams(window.location.search).get("page") || "dashboard");
  const [editingUser, setEditingUser] = useStateAD(null);
  const [editingCompany, setEditingCompany] = useStateAD(null);
  const [reportUser, setReportUser] = useStateAD(null);
  const [editingPurchase, setEditingPurchase] = useStateAD(null);
  const [users, setUsers] = useStateAD(() => loadStore(USERS_KEY, SEED_USERS));
  const [companies, setCompanies] = useStateAD(() => loadStore(COMPANIES_KEY, SEED_COMPANIES));
  const [toast, setToast] = useStateAD(null);

  useEffectAD(() => { saveStore(USERS_KEY, users); }, [users]);
  useEffectAD(() => { saveStore(COMPANIES_KEY, companies); }, [companies]);

  /* Shared state across devices (phone/desktop) via /api/store. */
  const remoteRev = useRefAD(0);
  const [remoteOn, setRemoteOn] = useStateAD(false);
  useEffectAD(() => {
    if (!window.remoteGet) { setRemoteOn(true); return; }
    let stop = false;
    (async () => {
      const s = await window.remoteGet();
      if (!stop && s && s.users && s.users.length) {
        remoteRev.current = s.rev || 0;
        setUsers(s.users);
        setCompanies(s.companies || []);
      }
      if (!stop) setRemoteOn(true);
    })();
    const id = setInterval(async () => {
      const s = await window.remoteGet();
      if (stop || !s) return;
      if ((s.rev || 0) > remoteRev.current) {
        remoteRev.current = s.rev || 0;
        setUsers(s.users);
        setCompanies(s.companies || []);
      }
    }, 4000);
    return () => { stop = true; clearInterval(id); };
  }, []);
  useEffectAD(() => {
    if (remoteOn && window.remotePut) window.remotePut(users, companies);
  }, [users, companies, remoteOn]);
  useEffectAD(() => { localStorage.setItem("aur.admin.page", page); }, [page]);
  useEffectAD(() => {
    const onStorage = (e) => {
      if (e.key === USERS_KEY && e.newValue) {
        try { setUsers(JSON.parse(e.newValue)); } catch (_) {}
      } else if (e.key === COMPANIES_KEY && e.newValue) {
        try { setCompanies(JSON.parse(e.newValue)); } catch (_) {}
      }
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);
  useEffectAD(() => { if (!toast) return; const id = setTimeout(() => setToast(null), 2200); return () => clearTimeout(id); }, [toast]);

  const upsertUser = (originalEmail, patch) => {
    setUsers(prev => {
      const i = prev.findIndex(u => u.email.toLowerCase() === (originalEmail || "").toLowerCase());
      if (i === -1) return [patch, ...prev];
      const next = prev.slice(); next[i] = { ...next[i], ...patch }; return next;
    });
  };
  const removeUser = (email) => setUsers(prev => prev.filter(u => u.email.toLowerCase() !== email.toLowerCase()));

  const upsertCompany = (originalEmail, patch) => {
    setCompanies(prev => {
      const i = prev.findIndex(c => c.email.toLowerCase() === (originalEmail || "").toLowerCase());
      if (i === -1) return [patch, ...prev];
      const next = prev.slice(); next[i] = { ...next[i], ...patch }; return next;
    });
  };
  const removeCompany = (email) => {
    setCompanies(prev => prev.filter(c => c.email.toLowerCase() !== email.toLowerCase()));
    setUsers(prev => prev.map(u => u.company === email ? { ...u, company: "" } : u));
  };

  const isDe = lang === "de";

  // Routing
  let body = null;
  if (page === "dashboard")           body = <AdminDashboardV2 users={users} companies={companies} go={setPage} lang={lang} />;
  else if (page === "users")          body = <AllUsers lang={lang} users={users} companies={companies}
                                                onEdit={(email) => setEditingUser(email)} onCreate={() => setPage("users-create")}
                                                onReport={(email) => { setReportUser(email); setPage("report"); }}
                                                onDelete={(email) => { if (window.confirm(isDe ? "Benutzer löschen?" : "Delete user?")) { removeUser(email); setToast(isDe ? "Benutzer gelöscht" : "User deleted"); } }} />;
  else if (page === "users-create")   body = <UserForm lang={lang} mode="new" companies={companies}
                                                onCancel={() => setPage("users")}
                                                onSave={(u) => { upsertUser("", u); setPage("users"); setToast((isDe ? "Benutzer angelegt · " : "User created · ") + u.name); }} />;
  else if (page === "companies")      body = <AllCompanies lang={lang} companies={companies} users={users}
                                                onEdit={(email) => setEditingCompany(email)} onCreate={() => setPage("companies-create")}
                                                onDelete={(email) => { if (window.confirm(isDe ? "Unternehmen löschen? Mitglieder werden entkoppelt." : "Delete company? Members will be unassigned.")) { removeCompany(email); setToast(isDe ? "Unternehmen gelöscht" : "Company deleted"); } }} />;
  else if (page === "companies-create") body = <CompanyForm lang={lang} mode="new" users={users}
                                                onCancel={() => setPage("companies")}
                                                onSave={(c) => {
                                                  const { __quickPurchase, ...co } = c;
                                                  upsertCompany("", co);
                                                  if (__quickPurchase && __quickPurchase.userEmail) {
                                                    setUsers(prev => prev.map(u => {
                                                      if (u.email.toLowerCase() !== __quickPurchase.userEmail.toLowerCase()) return u;
                                                      const list = Array.isArray(u.companies) ? u.companies.slice() : (u.company ? [u.company] : []);
                                                      if (!list.includes(co.email)) list.push(co.email);
                                                      return { ...u, companies: list, company: u.company || co.email };
                                                    }));
                                                  }
                                                  setPage("companies");
                                                  setToast((isDe ? "Unternehmen angelegt · " : "Company created · ") + co.name);
                                                }} />;
  else if (page === "purchases")      body = <AllPurchases lang={lang} users={users} companies={companies}
                                                onCreate={() => { setEditingPurchase(null); setPage("purchases-create"); }}
                                                onEdit={(p) => { setEditingPurchase(p); setPage("purchases-edit"); }}
                                                onPatch={(p, patch) => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== p.userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).map(l => l.id === p.lotId ? { ...l, ...patch } : l);
                                                    return withLots(u, lots);
                                                  }));
                                                }}
                                                onReseed={() => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== "j.diehl@example.de") return u;
                                                    const has = getUserLots(u).some(l => l.id === "lot-sap-seed");
                                                    const lots = has
                                                      ? getUserLots(u).map(l => l.id === "lot-sap-seed" ? { ...l, lockUntil: "2027-01-01", note: "Verkaufssperre bis 01.01.2027 (Haltefrist)." } : l)
                                                      : [{ id: "lot-sap-seed", companyEmail: "ir@sap.com", qty: 250, buyPrice: 188.4, buyDate: "2025-01-01", payment: "paid", lockUntil: "2027-01-01", note: "Verkaufssperre bis 01.01.2027 (Haltefrist)." }, ...getUserLots(u)];
                                                    return withLots(u, lots);
                                                  }));
                                                  setToast(isDe ? "Demo-Sperre wiederhergestellt" : "Demo lock restored");
                                                }}
                                                onSetPay={(p, state) => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== p.userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).map(l => l.id === p.lotId ? { ...l, payment: state } : l);
                                                    return withLots(u, lots);
                                                  }));
                                                  setToast(state === "paid" ? (isDe ? "Als bezahlt markiert" : "Marked as paid") : (isDe ? "Auf ausstehend gesetzt" : "Set to pending"));
                                                }}
                                                onDelete={(p) => {
                                                  if (!window.confirm(isDe ? "Diesen Kauf löschen?" : "Delete this purchase?")) return;
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== p.userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).filter(l => l.id !== p.lotId);
                                                    return withLots(u, lots);
                                                  }));
                                                  setToast(isDe ? "Kauf gelöscht" : "Purchase deleted");
                                                }} />;
  else if (page === "purchases-create") body = <PurchaseForm lang={lang} mode="new" users={users} companies={companies}
                                                onCancel={() => setPage("purchases")}
                                                onSave={(p) => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== p.userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).slice();
                                                    lots.push({ id: newLotId(), companyEmail: p.companyEmail, qty: p.qty, buyPrice: p.buyPrice, buyDate: p.buyDate || null, payment: p.payment || "pending", lockUntil: p.lockUntil || null, note: p.note || "" });
                                                    return withLots(u, lots);
                                                  }));
                                                  setPage("purchases"); setToast(isDe ? "Kauf erfasst" : "Purchase created");
                                                }} />;
  else if (page === "purchases-edit") body = <PurchaseForm lang={lang} mode="edit" initial={editingPurchase} users={users} companies={companies}
                                                onCancel={() => setPage("purchases")}
                                                onSave={(p) => {
                                                  const orig = editingPurchase;
                                                  setUsers(prev => prev.map(u => {
                                                    if (orig && u.email.toLowerCase() === orig.userEmail.toLowerCase()) {
                                                      let lots = getUserLots(u).filter(l => l.id !== orig.lotId);
                                                      if (u.email.toLowerCase() === p.userEmail.toLowerCase()) {
                                                        lots = lots.concat([{ id: orig.lotId, companyEmail: p.companyEmail, qty: p.qty, buyPrice: p.buyPrice, buyDate: p.buyDate || null, payment: p.payment || "pending", lockUntil: p.lockUntil || null, note: p.note || "" }]);
                                                      }
                                                      return withLots(u, lots);
                                                    }
                                                    if (u.email.toLowerCase() === p.userEmail.toLowerCase()) {
                                                      const lots = getUserLots(u).concat([{ id: newLotId(), companyEmail: p.companyEmail, qty: p.qty, buyPrice: p.buyPrice, buyDate: p.buyDate || null, payment: p.payment || "pending", lockUntil: p.lockUntil || null, note: p.note || "" }]);
                                                      return withLots(u, lots);
                                                    }
                                                    return u;
                                                  }));
                                                  setPage("purchases"); setToast(isDe ? "Kauf aktualisiert" : "Purchase updated");
                                                }} />;
  else if (page === "report")         body = <ReportPage lang={lang} userEmail={reportUser} users={users} companies={companies}
                                                onBack={() => setPage("users")}
                                                onAssign={(userEmail, companyEmail, buyPrice) => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).concat([{ id: newLotId(), companyEmail, qty: null, buyPrice: buyPrice != null ? buyPrice : null, buyDate: new Date().toISOString().slice(0, 10), payment: "pending", lockUntil: null, note: "" }]);
                                                    return withLots(u, lots);
                                                  }));
                                                }}
                                                onSetLot={(userEmail, lotId, patch) => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).map(l => l.id === lotId ? { ...l, ...patch } : l);
                                                    return withLots(u, lots);
                                                  }));
                                                }}
                                                onRemoveLot={(userEmail, lotId) => {
                                                  setUsers(prev => prev.map(u => {
                                                    if (u.email.toLowerCase() !== userEmail.toLowerCase()) return u;
                                                    const lots = getUserLots(u).filter(l => l.id !== lotId);
                                                    return withLots(u, lots);
                                                  }));
                                                }}
                                                onSetRemarks={(userEmail, remarks) => {
                                                  setUsers(prev => prev.map(u => u.email.toLowerCase() === userEmail.toLowerCase() ? { ...u, reportRemarks: remarks } : u));
                                                }} />;
  else if (page === "terms")          body = <TermsPage lang={lang} />;
  else if (page === "settings")       body = <SiteSettingsPage lang={lang} onSaved={() => setToast(isDe ? "Einstellungen gespeichert" : "Settings saved")} />;
  else if (page === "profile")        body = <AdminProfilePage lang={lang} onSaved={() => setToast(isDe ? "Profil gespeichert" : "Profile saved")} onCancel={() => setPage("dashboard")} />;
  else                                body = <AdminDashboardV2 users={users} companies={companies} go={setPage} lang={lang} />;

  const editingUserObj    = editingUser ? users.find(u => u.email === editingUser) : null;
  const editingCompanyObj = editingCompany ? companies.find(c => c.email === editingCompany) : null;

  return (
    <div className="adm-shell">
      <AdminSidebar page={page} setPage={setPage} onLogout={onLogout} lang={lang} />
      <div className="adm-main">
        <AdminTopbar page={page} lang={lang} />
        <div className="adm-body">{body}</div>
      </div>

      {editingUserObj && (
        <UserModal lang={lang} initial={editingUserObj} companies={companies}
          existingEmails={users.map(u => u.email.toLowerCase())}
          onClose={() => setEditingUser(null)}
          onSave={(orig, next) => { upsertUser(orig, next); setEditingUser(null); setToast((isDe ? "Gespeichert · " : "Saved · ") + next.name); }}
          onDelete={(email) => { if (!window.confirm(isDe ? "Benutzer löschen?" : "Delete user?")) return; removeUser(email); setEditingUser(null); setToast(isDe ? "Benutzer gelöscht" : "User deleted"); }}
        />
      )}
      {editingCompanyObj && (
        <CompanyModal lang={lang} initial={editingCompanyObj}
          existingEmails={companies.map(c => c.email.toLowerCase())}
          onClose={() => setEditingCompany(null)}
          onSave={(orig, next) => { upsertCompany(orig, next); setEditingCompany(null); setToast((isDe ? "Gespeichert · " : "Saved · ") + next.name); }}
          onDelete={(email) => { if (!window.confirm(isDe ? "Unternehmen löschen?" : "Delete company?")) return; removeCompany(email); setEditingCompany(null); setToast(isDe ? "Unternehmen gelöscht" : "Company deleted"); }}
        />
      )}

      {toast && <div className="adm-toast">● {toast}</div>}
    </div>
  );
}

/* =========================================================
   Sidebar
   ========================================================= */
function AdminSidebar({ page, setPage, onLogout, lang }) {
  const isDe = lang === "de";
  const L = isDe ? {
    nav: "NAVIGATION",
    dashboard: "Übersicht",
    users: "Kunden",
    allUsers: "Alle Kunden",
    createUser: "Kunde anlegen",
    companies: "Beteiligungen",
    allCompanies: "Alle Beteiligungen",
    createCompany: "Beteiligung anlegen",
    purchases: "Käufe",
    allPurchases: "Alle Käufe",
    newPurchase: "Neuer Kauf",
    terms: "Nutzungsbedingungen",
    profile: "Profil",
    settings: "WhatsApp & Logo",
    logout: "Abmelden",
  } : {
    nav: "NAVIGATION",
    dashboard: "Dashboard",
    users: "Clients",
    allUsers: "All clients",
    createUser: "Create client",
    companies: "Holdings",
    allCompanies: "All holdings",
    createCompany: "Create holding",
    purchases: "Purchases",
    allPurchases: "All purchases",
    newPurchase: "New purchase",
    terms: "Terms of use",
    profile: "Profile",
    settings: "WhatsApp & Logo",
    logout: "Logout",
  };
  const [usersOpen, setUsersOpen] = useStateAD(true);
  const [coOpen, setCoOpen] = useStateAD(true);
  const [prOpen, setPrOpen] = useStateAD(true);
  const Item = ({ id, icon, label, active, onClick, indent }) => (
    <button className={"adm-navitem" + (active ? " on" : "") + (indent ? " indent" : "")} onClick={onClick}>
      {icon && <span className="adm-navicon">{icon}</span>}
      <span>{label}</span>
    </button>
  );
  return (
    <aside className="adm-sidebar">
      <div className="adm-brand">
        <div className="adm-brandmark">AF</div>
        <div>
          <div className="adm-brandname">Aurevon</div>
          <div className="adm-brandsub">Desk-Konsole</div>
        </div>
      </div>
      <div className="adm-navlabel">{L.nav}</div>
      <nav className="adm-nav">
        <Item id="dashboard" icon={<IconGrid />} label={L.dashboard} active={page === "dashboard"} onClick={() => setPage("dashboard")} />

        <button className={"adm-navgroup" + (page.startsWith("users") ? " on" : "")} onClick={() => setUsersOpen(o => !o)}>
          <span className="adm-navicon"><IconUsers /></span>
          <span style={{ flex: 1, textAlign: "left" }}>{L.users}</span>
          <span className="adm-caret" style={{ transform: usersOpen ? "rotate(180deg)" : "" }}>▾</span>
        </button>
        {usersOpen && (
          <>
            <Item id="users" label={L.allUsers} indent active={page === "users"} onClick={() => setPage("users")} />
            <Item id="users-create" label={L.createUser} indent active={page === "users-create"} onClick={() => setPage("users-create")} />
          </>
        )}

        <button className={"adm-navgroup" + (page.startsWith("companies") ? " on" : "")} onClick={() => setCoOpen(o => !o)}>
          <span className="adm-navicon"><IconBuilding /></span>
          <span style={{ flex: 1, textAlign: "left" }}>{L.companies}</span>
          <span className="adm-caret" style={{ transform: coOpen ? "rotate(180deg)" : "" }}>▾</span>
        </button>
        {coOpen && (
          <>
            <Item id="companies" label={L.allCompanies} indent active={page === "companies"} onClick={() => setPage("companies")} />
            <Item id="companies-create" label={L.createCompany} indent active={page === "companies-create"} onClick={() => setPage("companies-create")} />
          </>
        )}

        <button className={"adm-navgroup" + (page.startsWith("purchases") ? " on" : "")} onClick={() => setPrOpen(o => !o)}>
          <span className="adm-navicon"><IconCart /></span>
          <span style={{ flex: 1, textAlign: "left" }}>{L.purchases}</span>
          <span className="adm-caret" style={{ transform: prOpen ? "rotate(180deg)" : "" }}>▾</span>
        </button>
        {prOpen && (
          <>
            <Item id="purchases" label={L.allPurchases} indent active={page === "purchases"} onClick={() => setPage("purchases")} />
            <Item id="purchases-create" label={L.newPurchase} indent active={page === "purchases-create"} onClick={() => setPage("purchases-create")} />
          </>
        )}

        <div className="adm-divider"></div>
        <Item id="terms" icon={<IconDoc />} label={L.terms} active={page === "terms"} onClick={() => setPage("terms")} />
        <Item id="settings" icon={<IconGear />} label={L.settings} active={page === "settings"} onClick={() => setPage("settings")} />
        <Item id="profile" icon={<IconUser />} label={L.profile} active={page === "profile"} onClick={() => setPage("profile")} />
        <Item id="logout" icon={<IconLogout />} label={L.logout} onClick={onLogout} />
      </nav>
      <div className="adm-foot">
        <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, color: "#5d5d67" }}>v3.0.0 · DESK</div>
      </div>
    </aside>
  );
}

function AdminTopbar({ page, lang }) {
  const isDe = lang === "de";
  const titles = isDe ? {
    "dashboard": "Übersicht",
    "users": "Alle Kunden",
    "users-create": "Kunde anlegen",
    "companies": "Alle Beteiligungen",
    "companies-create": "Beteiligung anlegen",
    "purchases": "Käufe",
    "purchases-create": "Neuer Kauf",
    "purchases-edit": "Kauf bearbeiten",
    "report": "Kundenbericht",
    "terms": "Nutzungsbedingungen",
    "profile": "Profil bearbeiten",
    "settings": "WhatsApp & Logo",
  } : {
    "dashboard": "Dashboard",
    "users": "All clients",
    "users-create": "Create client",
    "companies": "All holdings",
    "companies-create": "Create holding",
    "purchases": "Purchases",
    "purchases-create": "New purchase",
    "purchases-edit": "Edit purchase",
    "report": "Client report",
    "terms": "Terms of use",
    "profile": "Edit profile",
    "settings": "WhatsApp & Logo",
  };
  return (
    <div className="adm-topbar">
      <div>
        <div className="adm-crumb">{isDe ? "DESK" : "DESK"} / {titles[page] || page}</div>
        <h1 className="adm-h1">{titles[page] || page}</h1>
      </div>
      <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
        <div className="lang-toggle" style={{ border: "1px solid var(--adm-line)", display: "flex", borderRadius: 4, overflow: "hidden" }}>
          <button onClick={() => window.__setLang && window.__setLang("de")}
            style={{ background: isDe ? "#1f1f24" : "transparent", color: isDe ? "#fff" : "#82828d", border: "none", padding: "6px 12px", fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.08em", cursor: "pointer" }}>DE</button>
          <button onClick={() => window.__setLang && window.__setLang("en")}
            style={{ background: !isDe ? "#1f1f24" : "transparent", color: !isDe ? "#fff" : "#82828d", border: "none", padding: "6px 12px", fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.08em", cursor: "pointer" }}>EN</button>
        </div>
        <span className="adm-pill"><span style={{ width: 6, height: 6, borderRadius: 999, background: "#34d399", display: "inline-block", marginRight: 6 }}></span>XETRA</span>
        <div className="adm-avatar">D</div>
      </div>
    </div>
  );
}

/* =========================================================
   Dashboard
   ========================================================= */
function AdminDashboardV2({ users, companies, go, lang }) {
  const isDe = lang === "de";
  const verified = users.filter(u => u.status === "verified").length;
  const pending = users.filter(u => u.status === "pending").length;
  return (
    <div>
      <div className="adm-grid4">
        <DashCard label={isDe ? "Kunden gesamt" : "Total clients"} value={users.length} delta={isDe ? "+ diesen Monat" : "+ this month"} tone="brass" onClick={() => go("users")} />
        <DashCard label={isDe ? "Beteiligungen" : "Holdings"} value={companies.length} delta={isDe ? "aktive Positionen" : "active positions"} tone="violet" onClick={() => go("companies")} />
        <DashCard label={isDe ? "Verifiziert" : "Verified"} value={verified} delta={isDe ? "freigegeben" : "onboarded"} tone="green" />
        <DashCard label={isDe ? "In Prüfung" : "Pending"} value={pending} delta={isDe ? "zu prüfen" : "needs review"} tone="amber" />
      </div>
      <div className="adm-card" style={{ marginTop: 24 }}>
        <div className="adm-card-h">
          <div className="adm-card-title">{isDe ? "Letzte Aktivität" : "Recent activity"}</div>
          <span style={{ fontSize: 11.5, color: "#82828d" }}>{isDe ? "letzte 24 h" : "last 24h"}</span>
        </div>
        <ul className="adm-activity">
          {users.slice(0, 5).map(u => (
            <li key={u.email}>
              <span className="adm-dot"></span>
              <span style={{ flex: 1 }}><b>{u.name}</b> {isDe ? "registriert" : "registered"}</span>
              <span style={{ color: "#82828d", fontFamily: "var(--mono)", fontSize: 10.5 }}>{u.email}</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
function DashCard({ label, value, delta, tone, onClick }) {
  const map = { brass: "#c2a06a", violet: "#8b5cf6", green: "#34d399", amber: "#fbbf24" };
  return (
    <button className="adm-stat" onClick={onClick} style={{ borderLeft: "3px solid " + map[tone] }}>
      <div className="adm-stat-l">{label}</div>
      <div className="adm-stat-v">{value}</div>
      <div className="adm-stat-d">{delta}</div>
    </button>
  );
}

/* =========================================================
   ALL USERS
   ========================================================= */
function AllUsers({ lang, users, companies, onEdit, onCreate, onDelete, onReport }) {
  const isDe = lang === "de";
  const [pageSize, setPageSize] = useStateAD(10);
  const [pageNum, setPageNum] = useStateAD(1);
  const [query, setQuery] = useStateAD("");
  const [sort, setSort] = useStateAD({ k: "name", d: 1 });

  const filtered = useMemoAD(() => {
    const q = query.trim().toLowerCase();
    let arr = users.filter(u => {
      if (!q) return true;
      return u.name.toLowerCase().includes(q)
          || u.email.toLowerCase().includes(q)
          || (u.phone || "").toLowerCase().includes(q)
          || (u.address || "").toLowerCase().includes(q);
    });
    arr = arr.slice().sort((a, b) => {
      const av = (a[sort.k] || "").toString().toLowerCase();
      const bv = (b[sort.k] || "").toString().toLowerCase();
      return av.localeCompare(bv, "de") * sort.d;
    });
    return arr;
  }, [users, query, sort]);

  useEffectAD(() => { setPageNum(1); }, [query, pageSize]);
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const start = (pageNum - 1) * pageSize;
  const visible = filtered.slice(start, start + pageSize);

  const sortBy = (k) => setSort(s => s.k === k ? { k, d: -s.d } : { k, d: 1 });
  const Th = ({ k, children, align }) => (
    <th onClick={() => sortBy(k)} style={{ textAlign: align || "left", cursor: "pointer" }}>
      {children}
      <span style={{ marginLeft: 6, color: sort.k === k ? "#fff" : "#3a3a42", fontSize: 10 }}>
        {sort.k === k ? (sort.d === 1 ? "▲" : "▼") : "⇅"}
      </span>
    </th>
  );

  return (
    <div className="adm-card">
      <div className="adm-tbl-tools">
        <label className="adm-show">
          {isDe ? "Zeige" : "Show"}
          <select value={pageSize} onChange={(e) => setPageSize(parseInt(e.target.value, 10))}>
            <option>5</option><option>10</option><option>25</option><option>50</option>
          </select>
          {isDe ? "Einträge" : "entries"}
        </label>
        <div style={{ flex: 1 }}></div>
        <button className="adm-btn-primary" onClick={onCreate}>+ {isDe ? "Kunde anlegen" : "Create client"}</button>
        <div className="adm-search">
          <input placeholder={isDe ? "SUCHE:" : "SEARCH:"} value={query} onChange={(e) => setQuery(e.target.value)} />
        </div>
      </div>

      <table className="adm-tbl">
        <thead>
          <tr>
            <Th k="name">{isDe ? "NAME" : "NAME"}</Th>
            <Th k="email">E-MAIL</Th>
            <Th k="address">{isDe ? "ADRESSE" : "ADDRESS"}</Th>
            <Th k="phone">{isDe ? "TELEFON" : "PHONE"}</Th>
            <Th k="status">STATUS</Th>
            <th style={{ textAlign: "center" }}>{isDe ? "AKTIONEN" : "ACTIONS"}</th>
          </tr>
        </thead>
        <tbody>
          {visible.length === 0 ? (
            <tr><td colSpan={6} style={{ padding: "60px 20px", textAlign: "center", color: "#82828d" }}>{isDe ? "Keine Kunden gefunden." : "No clients found."}</td></tr>
          ) : visible.map(u => {
            const co = companies.find(c => c.email === u.company);
            return (
              <tr key={u.email}>
                <td>
                  <div style={{ display: "flex", flexDirection: "column" }}>
                    <span style={{ color: "#fff", fontWeight: 500 }}><Hi text={u.name} q={query} /></span>
                    {co && <span style={{ fontSize: 10.5, color: "#82828d" }}>{co.name}</span>}
                  </div>
                </td>
                <td className="adm-link"><Hi text={u.email} q={query} /></td>
                <td style={{ color: u.address && u.address !== "-" ? "#a8a8b1" : "#5d5d67" }}>{u.address || "—"}</td>
                <td style={{ color: "#fff", fontWeight: 500 }}><Hi text={u.phone || "—"} q={query} /></td>
                <td><StatusPill status={u.status} lang={lang} /></td>
                <td>
                  <div className="adm-actions">
                    <button className="adm-link-btn" onClick={() => onReport && onReport(u.email)}>{isDe ? "BERICHT" : "REPORT"}</button>
                    <button className="adm-iconbtn" onClick={() => onEdit(u.email)} title={isDe ? "Bearbeiten" : "Edit"}><IconEdit /></button>
                    <button className="adm-iconbtn danger" onClick={() => onDelete(u.email)} title={isDe ? "Löschen" : "Delete"}><IconTrash /></button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>

      <div className="adm-tbl-foot">
        <div style={{ color: "#82828d", fontSize: 12.5 }}>
          {isDe ? "Zeilen" : "Showing"} {filtered.length === 0 ? 0 : start + 1}–{Math.min(start + pageSize, filtered.length)} {isDe ? "von" : "of"} {filtered.length}
          {users.length !== filtered.length && <span style={{ color: "#5d5d67" }}> ({isDe ? "gefiltert aus" : "filtered from"} {users.length})</span>}
        </div>
        <Pager page={pageNum} totalPages={totalPages} onPage={setPageNum} lang={lang} />
      </div>
    </div>
  );
}

/* =========================================================
   ALL COMPANIES
   ========================================================= */
function AllCompanies({ lang, companies, users, onEdit, onCreate, onDelete }) {
  const isDe = lang === "de";
  const [pageSize, setPageSize] = useStateAD(10);
  const [pageNum, setPageNum] = useStateAD(1);
  const [query, setQuery] = useStateAD("");

  const filtered = useMemoAD(() => {
    const q = query.trim().toLowerCase();
    return companies.filter(c => !q
      || c.name.toLowerCase().includes(q)
      || (c.symbol || "").toLowerCase().includes(q)
      || (c.wkn || "").toLowerCase().includes(q)
      || (c.isin || "").toLowerCase().includes(q));
  }, [companies, query]);
  useEffectAD(() => { setPageNum(1); }, [query, pageSize]);
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const start = (pageNum - 1) * pageSize;
  const visible = filtered.slice(start, start + pageSize);

  const fmtMoney = (n) => (Number(n) || 0).toLocaleString("de-DE", { style: "currency", currency: "EUR", minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const fmtNum = (n) => (Number(n) || 0).toLocaleString("de-DE");

  return (
    <div className="adm-card">
      <div className="adm-tbl-tools">
        <label className="adm-show">
          {isDe ? "Zeige" : "Show"}
          <select value={pageSize} onChange={(e) => setPageSize(parseInt(e.target.value, 10))}>
            <option>5</option><option>10</option><option>25</option><option>50</option>
          </select>
          {isDe ? "Einträge" : "entries"}
        </label>
        <div style={{ flex: 1 }}></div>
        <button className="adm-btn-primary" onClick={onCreate}>+ {isDe ? "Beteiligung anlegen" : "New holding"}</button>
        <div className="adm-search">
          <input placeholder={isDe ? "SUCHE:" : "SEARCH:"} value={query} onChange={(e) => setQuery(e.target.value)} />
        </div>
      </div>
      <table className="adm-tbl">
        <thead>
          <tr>
            <th>NAME</th>
            <th>SYMBOL</th>
            <th style={{ textAlign: "right" }}>{isDe ? "ANTEILE" : "TOTAL SHARES"}</th>
            <th style={{ textAlign: "right" }}>{isDe ? "EINSTAND" : "BUY PRICE"}</th>
            <th style={{ textAlign: "right" }}>{isDe ? "KURS" : "CURRENT PRICE"}</th>
            <th style={{ textAlign: "center" }}>{isDe ? "AKTIONEN" : "ACTIONS"}</th>
          </tr>
        </thead>
        <tbody>
          {visible.length === 0 ? (
            <tr><td colSpan={6} style={{ padding: "60px 20px", textAlign: "center", color: "#82828d" }}>{isDe ? "Keine Beteiligungen gefunden." : "No holdings found."}</td></tr>
          ) : visible.map(c => {
            const buy = c.buyPrice ?? 0;
            const curr = c.sharePrice ?? c.currentPrice ?? 0;
            const up = curr >= buy;
            const symbolText = c.wkn && c.isin
              ? `WKN: ${c.wkn} · ISIN: ${c.isin}`
              : (c.symbol || "—").toUpperCase();
            return (
              <tr key={c.email}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div className="adm-co-mark">{c.name[0]}</div>
                    <div style={{ color: "#fff", fontWeight: 500 }}><Hi text={c.name} q={query} /></div>
                  </div>
                </td>
                <td style={{ color: "#a8a8b1", fontFamily: "var(--mono)", fontSize: 11.5 }}><Hi text={symbolText} q={query} /></td>
                <td style={{ textAlign: "right", color: "#fff", fontFamily: "var(--mono)" }}>{fmtNum(c.totalShares)}</td>
                <td style={{ textAlign: "right", color: "#a8a8b1", fontFamily: "var(--mono)" }}>{fmtMoney(buy)}</td>
                <td style={{ textAlign: "right", color: up ? "#34d399" : "#f87171", fontFamily: "var(--mono)", fontWeight: 500 }}>{fmtMoney(curr)}</td>
                <td>
                  <div className="adm-actions">
                    <button className="adm-iconbtn" onClick={() => onEdit(c.email)} title={isDe ? "Bearbeiten" : "Edit"}><IconEdit /></button>
                    <button className="adm-iconbtn danger" onClick={() => onDelete(c.email)} title={isDe ? "Löschen" : "Delete"}><IconTrash /></button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div className="adm-tbl-foot">
        <div style={{ color: "#82828d", fontSize: 12.5 }}>
          {isDe ? "Zeilen" : "Showing"} {filtered.length === 0 ? 0 : start + 1}–{Math.min(start + pageSize, filtered.length)} {isDe ? "von" : "of"} {filtered.length}
        </div>
        <Pager page={pageNum} totalPages={totalPages} onPage={setPageNum} lang={lang} />
      </div>
    </div>
  );
}

/* =========================================================
   Forms
   ========================================================= */
const ADVISOR_LIST = [
  "Dr. Katharina Reuter — Geschäftsführende Partnerin",
  "Sebastian Kolb — Partner, Portfolio",
  "Dr. Martin Eisele — Partner, Planung",
  "Aylin Demir — Leiterin Trading Desk",
  "Dr. Charlotte Muth — Senior Advisor",
];
const CURRENCY_LIST = ["EUR", "CHF", "USD", "GBP", "JPY"];

function UserForm({ lang, mode, companies, onCancel, onSave }) {
  const isDe = lang === "de";
  const T = isDe ? {
    title: "Neuer Kunde",
    sub: "Tragen Sie unten die Details ein, um ein Kundenkonto anzulegen. Nur das Desk kann diese Felder bearbeiten — Kunden sehen sie im Portal schreibgeschützt.",
    personal: "Persönliche Angaben",
    firstName: "Vorname", lastName: "Nachname",
    email: "E-Mail-Adresse", phone: "Telefonnummer",
    security: "Sicherheit",
    password: "Passwort", confirm: "Passwort bestätigen",
    pwPh: "Mind. 8 Zeichen", confirmPh: "Passwort wiederholen",
    settings: "Kontoeinstellungen",
    advisor: "Zuständiger Berater", advisorHint: "Vor- und Nachname des Beraters. Der Kunde sieht diesen im Portal.", advisorPh: "z. B. Dr. Katharina Reuter",
    currency: "Währung", status: "Status",
    companies: "Beteiligungen (⌘/Strg für Mehrfachauswahl)", companiesHint: "Ordnen Sie eine oder mehrere Beteiligungen zu. Nur Desk.",
    role: "Rolle im Depot",
    additional: "Zusätzliche Angaben",
    address: "Adresse", addressPh: "Straße, PLZ, Ort",
    remarks: "Anmerkungen", remarksPh: "Notizen zu diesem Kunden…",
    cancel: "Abbrechen", submit: "Kunde anlegen →",
    required: "Erforderlich", invalidEmail: "Ungültige E-Mail", minChars: "Min. 8 Zeichen", noMatch: "Passwörter stimmen nicht überein",
  } : {
    title: "New client",
    sub: "Fill in the details below to create a client account. Admin-only — clients see these fields read-only in their portal.",
    personal: "Personal information",
    firstName: "First name", lastName: "Last name",
    email: "Email address", phone: "Phone number",
    security: "Security",
    password: "Password", confirm: "Confirm password",
    pwPh: "Min. 8 characters", confirmPh: "Repeat password",
    settings: "Account settings",
    advisor: "Responsible advisor", advisorHint: "Name of the assigned advisor. The client sees this in their portal.", advisorPh: "e.g. Dr. Katharina Reuter",
    currency: "Currency", status: "Status",
    companies: "Holdings (hold ⌘/Ctrl to select multiple)", companiesHint: "Assign one or more holdings to this client. Admin-only.",
    role: "Role in custody account",
    additional: "Additional information",
    address: "Address", addressPh: "Street, ZIP, city",
    remarks: "Remarks", remarksPh: "Any notes about this client…",
    cancel: "Cancel", submit: "Create client →",
    required: "Required", invalidEmail: "Invalid email", minChars: "Min 8 chars", noMatch: "Passwords do not match",
  };
  const [form, setForm] = useStateAD({
    firstName: "", lastName: "", email: "", phone: "",
    password: "", confirmPassword: "",
    advisor: "", currency: "EUR",
    address: "", remarks: "",
    status: "verified", company: "", role: "Member",
  });
  const [errors, setErrors] = useStateAD({});
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));
  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.firstName.trim()) er.firstName = T.required;
    if (!form.lastName.trim()) er.lastName = T.required;
    if (!form.email.trim()) er.email = T.required;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = T.invalidEmail;
    if (!form.password) er.password = T.required;
    else if (form.password.length < 8) er.password = T.minChars;
    if (form.password !== form.confirmPassword) er.confirmPassword = T.noMatch;
    if (Object.keys(er).length) { setErrors(er); return; }
    const name = `${form.firstName.trim()} ${form.lastName.trim()}`;
    onSave({ ...form, email: form.email.trim(), name, firstName: form.firstName.trim(), lastName: form.lastName.trim() });
  };
  return (
    <form onSubmit={submit} className="adm-card" style={{ padding: 28 }}>
      <div className="adm-form-h">{T.title}</div>
      <p className="adm-form-sub">{T.sub}</p>

      <FormSection icon="user" title={T.personal} />
      <div className="adm-form-grid">
        <FormField label={T.firstName} error={errors.firstName}>
          <input value={form.firstName} onChange={(e) => set("firstName", e.target.value)} autoFocus />
        </FormField>
        <FormField label={T.lastName} error={errors.lastName}>
          <input value={form.lastName} onChange={(e) => set("lastName", e.target.value)} />
        </FormField>
        <FormField label={T.email} error={errors.email}>
          <input value={form.email} onChange={(e) => set("email", e.target.value)} type="email" placeholder="kunde@example.de" />
        </FormField>
        <FormField label={T.phone}>
          <input value={form.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+49 711 000 000" />
        </FormField>
      </div>

      <FormSection icon="lock" title={T.security} />
      <div className="adm-form-grid">
        <FormField label={T.password} error={errors.password}>
          <input value={form.password} onChange={(e) => set("password", e.target.value)} type="password" placeholder={T.pwPh} />
        </FormField>
        <FormField label={T.confirm} error={errors.confirmPassword}>
          <input value={form.confirmPassword} onChange={(e) => set("confirmPassword", e.target.value)} type="password" placeholder={T.confirmPh} />
        </FormField>
      </div>

      <FormSection icon="gear" title={T.settings} />
      <div className="adm-form-grid">
        <FormField label={T.advisor} hint={T.advisorHint}>
          <input value={form.advisor} onChange={(e) => set("advisor", e.target.value)} placeholder={T.advisorPh} list="advisor-list" />
        </FormField>
        <datalist id="advisor-list">
          {ADVISOR_LIST.map(a => <option key={a} value={a.split(" — ")[0]} />)}
        </datalist>
        <FormField label={T.currency}>
          <select value={form.currency} onChange={(e) => set("currency", e.target.value)}>
            {CURRENCY_LIST.map(c => <option key={c} value={c}>{c}</option>)}
          </select>
        </FormField>
        <FormField label={T.status}>
          <select value={form.status} onChange={(e) => set("status", e.target.value)}>
            {STATUS_OPTIONS.map(s => <option key={s.value} value={s.value}>{statusLabel(s, lang)}</option>)}
          </select>
        </FormField>
        <FormField label={T.companies} full hint={T.companiesHint}>
          <select multiple value={Array.isArray(form.companies) ? form.companies : (form.company ? [form.company] : [])}
            onChange={(e) => {
              const list = Array.from(e.target.selectedOptions).map(o => o.value);
              setForm(p => ({ ...p, companies: list, company: list[0] || "" }));
            }}
            style={{ minHeight: 110 }}>
            {companies.map(c => <option key={c.email} value={c.email}>{c.name}{c.symbol ? ` · ${c.symbol}` : ""}</option>)}
          </select>
        </FormField>
        <FormField label={T.role} full>
          <select value={form.role === "Member" || form.role === "Viewer" || form.role === "Owner" ? form.role : "Member"} onChange={(e) => set("role", e.target.value)}>
            <option value="Owner">Owner</option><option value="Member">Member</option><option value="Viewer">Viewer</option>
          </select>
        </FormField>
      </div>

      <FormSection icon="doc" title={T.additional} />
      <div className="adm-form-grid">
        <FormField label={T.address}>
          <textarea rows={3} value={form.address} onChange={(e) => set("address", e.target.value)} placeholder={T.addressPh} />
        </FormField>
        <FormField label={T.remarks}>
          <textarea rows={3} value={form.remarks} onChange={(e) => set("remarks", e.target.value)} placeholder={T.remarksPh} />
        </FormField>
      </div>

      <div className="adm-form-foot">
        <button type="button" className="adm-btn-ghost" onClick={onCancel}>{T.cancel}</button>
        <button type="submit" className="adm-btn-primary">{T.submit}</button>
      </div>
    </form>
  );
}

function FormSection({ icon, title }) {
  const icons = {
    user: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4" /><path d="M4 21v-1a7 7 0 0 1 14 0v1" /></svg>,
    briefcase: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="7" width="18" height="13" rx="2" /><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2" /></svg>,
    trend: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 17l6-6 4 4 8-8" /><path d="M14 7h7v7" /></svg>,
    cart: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1.5" /><circle cx="18" cy="21" r="1.5" /><path d="M3 4h2l3 12h12l2-8H6" /></svg>,
    lock: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></svg>,
    gear: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.36.15.68.42.91.76.24.34.36.74.36 1.14V11a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" /></svg>,
    doc: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z" /><path d="M14 3v6h6" /><path d="M8 13h8M8 17h6" /></svg>,
  };
  return (
    <div className="adm-form-section">
      <div className="adm-form-section-head">
        <span className="adm-form-section-icon">{icons[icon]}</span>
        <span>{title}</span>
      </div>
      <div className="adm-form-section-divider"></div>
    </div>
  );
}

function CompanyForm({ lang, mode, users, onCancel, onSave }) {
  const isDe = lang === "de";
  const T = isDe ? {
    title: "Neue Beteiligung",
    sub: "Tragen Sie die Details ein, um eine Position anzulegen. Nur Desk — Kunden können Beteiligungen weder anlegen noch ändern.",
    coInfo: "Instrument",
    coName: "Bezeichnung",
    symbol: "Symbol",
    symbolHint: "Tickersymbol (z. B. SAP, SIE).",
    shareDetails: "Positionsdetails",
    totalShares: "Anteile gesamt",
    buyPrice: "Einstandspreis je Anteil",
    currentPrice: "Aktueller Kurs",
    quick: "Sofortkauf (optional)",
    quickSub: "Wählen Sie Kunde und Menge, um beim Anlegen direkt einen Kauf zu erfassen.",
    user: "Kunde",
    noPurchase: "— Kein Kauf —",
    qty: "Menge (Anteile)",
    qtyPh: "Anzahl Anteile",
    cancel: "Abbrechen",
    submit: "Beteiligung anlegen →",
    required: "Erforderlich",
    qtyRequired: "Erforderlich, wenn Kunde gewählt",
  } : {
    title: "New holding",
    sub: "Fill in the details to register a position. Admin-only — clients cannot create or edit holdings.",
    coInfo: "Instrument",
    coName: "Name",
    symbol: "Symbol",
    symbolHint: "Ticker symbol (e.g. SAP, SIE).",
    shareDetails: "Position details",
    totalShares: "Total shares",
    buyPrice: "Buy price per share",
    currentPrice: "Current price",
    quick: "Quick purchase (optional)",
    quickSub: "Select a client and quantity to record a purchase immediately.",
    user: "Client",
    noPurchase: "— No purchase —",
    qty: "Quantity (shares)",
    qtyPh: "Number of shares",
    cancel: "Cancel",
    submit: "Create holding →",
    required: "Required",
    qtyRequired: "Required when client is selected",
  };
  const [form, setForm] = useStateAD({
    name: "", symbol: "",
    totalShares: "", buyPrice: "", currentPrice: "",
    purchaseUser: "", purchaseQty: "",
    status: "verified",
  });
  const [errors, setErrors] = useStateAD({});
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));
  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = T.required;
    if (!form.symbol.trim()) er.symbol = T.required;
    if (form.purchaseUser && !form.purchaseQty) er.purchaseQty = T.qtyRequired;
    if (Object.keys(er).length) { setErrors(er); return; }
    const sym = form.symbol.trim().toLowerCase().replace(/[^a-z0-9]/g, "");
    const email = `${sym || "co"}@position.local`;
    const payload = {
      email,
      name: form.name.trim(),
      symbol: form.symbol.trim().toUpperCase(),
      totalShares: parseFloat(form.totalShares) || 0,
      buyPrice: parseFloat(form.buyPrice) || 0,
      sharePrice: parseFloat(form.currentPrice) || 0,
      currentPrice: parseFloat(form.currentPrice) || 0,
      status: form.status,
      trend: window.__atlasStores?.genTrend ? window.__atlasStores.genTrend(1) : [],
      __quickPurchase: form.purchaseUser
        ? { userEmail: form.purchaseUser, qty: parseFloat(form.purchaseQty) || 0 }
        : null,
    };
    onSave(payload);
  };
  return (
    <form onSubmit={submit} className="adm-card" style={{ padding: 28 }}>
      <div className="adm-form-h">{T.title}</div>
      <p className="adm-form-sub">{T.sub}</p>

      <FormSection icon="briefcase" title={T.coInfo} />
      <div className="adm-form-grid">
        <FormField label={T.coName} error={errors.name}>
          <input value={form.name} onChange={(e) => set("name", e.target.value)} autoFocus />
        </FormField>
        <FormField label={T.symbol} hint={T.symbolHint} error={errors.symbol}>
          <input value={form.symbol} onChange={(e) => set("symbol", e.target.value)} />
        </FormField>
      </div>

      <FormSection icon="trend" title={T.shareDetails} />
      <div className="adm-form-grid">
        <FormField label={T.totalShares}>
          <input value={form.totalShares} onChange={(e) => set("totalShares", e.target.value.replace(/[^0-9.]/g, ""))} placeholder="100000" inputMode="decimal" />
        </FormField>
        <FormField label={T.buyPrice}>
          <input value={form.buyPrice} onChange={(e) => set("buyPrice", e.target.value.replace(/[^0-9.]/g, ""))} placeholder="0,00" inputMode="decimal" />
        </FormField>
        <FormField label={T.currentPrice}>
          <input value={form.currentPrice} onChange={(e) => set("currentPrice", e.target.value.replace(/[^0-9.]/g, ""))} placeholder="0,00" inputMode="decimal" />
        </FormField>
      </div>

      <FormSection icon="cart" title={T.quick} />
      <p className="adm-form-sub" style={{ marginTop: -4, marginBottom: 4 }}>{T.quickSub}</p>
      <div className="adm-form-grid">
        <FormField label={T.user}>
          <select value={form.purchaseUser} onChange={(e) => set("purchaseUser", e.target.value)}>
            <option value="">{T.noPurchase}</option>
            {(users || []).map(u => <option key={u.email} value={u.email}>{u.name} · {u.email}</option>)}
          </select>
        </FormField>
        <FormField label={T.qty} error={errors.purchaseQty}>
          <input value={form.purchaseQty} onChange={(e) => set("purchaseQty", e.target.value.replace(/[^0-9.]/g, ""))} placeholder={T.qtyPh} inputMode="decimal" />
        </FormField>
      </div>

      <div className="adm-form-foot">
        <button type="button" className="adm-btn-ghost" onClick={onCancel}>{T.cancel}</button>
        <button type="submit" className="adm-btn-primary">{T.submit}</button>
      </div>
    </form>
  );
}

/* =========================================================
   Edit modals
   ========================================================= */
function UserModal({ lang, initial, companies, existingEmails, onClose, onSave, onDelete }) {
  const isDe = lang === "de";
  const orig = useRefAD(initial.email);
  const [form, setForm] = useStateAD(initial);
  const [errors, setErrors] = useStateAD({});
  const [showPw, setShowPw] = useStateAD(false);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));
  useEffectAD(() => {
    const fn = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", fn);
    return () => window.removeEventListener("keydown", fn);
  }, [onClose]);
  const save = () => {
    const er = {};
    if (!form.name.trim()) er.name = isDe ? "Erforderlich" : "Required";
    if (!form.email.trim()) er.email = isDe ? "Erforderlich" : "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = isDe ? "Ungültige E-Mail" : "Invalid email";
    else if (form.email.toLowerCase() !== orig.current.toLowerCase() && existingEmails.includes(form.email.toLowerCase())) er.email = isDe ? "Existiert bereits" : "Already exists";
    if (form.password && form.password.length < 4) er.password = isDe ? "Min. 4 Zeichen" : "Min 4 characters";
    if (Object.keys(er).length) { setErrors(er); return; }
    onSave(orig.current, { ...form, email: form.email.trim(), name: form.name.trim() });
  };
  const assignedCompanies = Array.isArray(form.companies) ? form.companies : (form.company ? [form.company] : []);
  return (
    <div className="adm-modal" onClick={onClose}>
      <div className="adm-modal-card" onClick={(e) => e.stopPropagation()}>
        <div className="adm-modal-h">
          <div>
            <div className="adm-modal-eyebrow">{isDe ? "KUNDE BEARBEITEN" : "EDIT CLIENT"}</div>
            <div className="adm-modal-title">{form.name}</div>
          </div>
          <button onClick={onClose} className="adm-iconbtn">✕</button>
        </div>
        <div className="adm-form-grid" style={{ padding: 28 }}>
          <FormField label={isDe ? "Vollständiger Name" : "Full name"} error={errors.name}><input value={form.name} onChange={(e) => set("name", e.target.value)} autoFocus /></FormField>
          <FormField label="E-Mail" error={errors.email}><input value={form.email} onChange={(e) => set("email", e.target.value)} type="email" /></FormField>
          <FormField label="Telefon"><input value={form.phone || ""} onChange={(e) => set("phone", e.target.value)} /></FormField>
          <FormField label="Adresse"><input value={form.address || ""} onChange={(e) => set("address", e.target.value)} /></FormField>
          <FormField label={isDe ? "Passwort (nur Desk)" : "Password (admin only)"} error={errors.password} hint={isDe ? "Setzt oder ändert das Login-Passwort. Nur das Desk sieht dieses Feld." : "Set or change the client's login password. Admin-only."}>
            <div style={{ position: "relative" }}>
              <input value={form.password || ""} onChange={(e) => set("password", e.target.value)} type={showPw ? "text" : "password"}
                className="adm-input" style={{ paddingRight: 40, width: "100%" }}
                placeholder={isDe ? "Neues Passwort" : "Type new password"} autoComplete="new-password" />
              <button type="button" onClick={() => setShowPw(v => !v)}
                title={showPw ? "Hide" : "Show"}
                style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", background: "transparent", border: "none", color: "#a8a8b1", cursor: "pointer", display: "grid", placeItems: "center", padding: 6 }}>
                {showPw
                  ? <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3l18 18"/><path d="M10.6 6.1a10.94 10.94 0 0 1 1.4-.1c6 0 10 6 10 6a17.6 17.6 0 0 1-3.1 4M6.6 7.6A17.5 17.5 0 0 0 2 12s4 6 10 6c1.6 0 3-.3 4.2-.8"/><path d="M9.9 9.9A3 3 0 0 0 12 15a3 3 0 0 0 2.1-5.1"/></svg>
                  : <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>}
              </button>
            </div>
          </FormField>
          <FormField label="Status">
            <select value={form.status} onChange={(e) => set("status", e.target.value)}>
              {STATUS_OPTIONS.map(s => <option key={s.value} value={s.value}>{statusLabel(s, lang)}</option>)}
            </select>
          </FormField>
          <FormField label={isDe ? "Beteiligungen (⌘/Strg für Mehrfachauswahl)" : "Holdings (hold ⌘/Ctrl to select multiple)"} full hint={isDe ? "Eine oder mehrere Beteiligungen zuordnen. Nur Desk." : "Assign one or more holdings. Admin-only."}>
            <select multiple value={assignedCompanies}
              onChange={(e) => {
                const list = Array.from(e.target.selectedOptions).map(o => o.value);
                setForm(p => ({ ...p, companies: list, company: list[0] || "" }));
              }}
              style={{ minHeight: 110 }}>
              {companies.map(c => <option key={c.email} value={c.email}>{c.name}{c.symbol ? ` · ${c.symbol.toUpperCase()}` : ""}</option>)}
            </select>
          </FormField>
        </div>
        <div className="adm-form-foot">
          <button onClick={() => onDelete(orig.current)} className="adm-btn-ghost" style={{ color: "#f87171", borderColor: "rgba(248,113,113,0.3)" }}>{isDe ? "Kunde löschen" : "Delete client"}</button>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={onClose} className="adm-btn-ghost">{isDe ? "Abbrechen" : "Cancel"}</button>
            <button onClick={save} className="adm-btn-primary">{isDe ? "Speichern →" : "Save changes →"}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function CompanyModal({ lang, initial, existingEmails, onClose, onSave, onDelete }) {
  const isDe = lang === "de";
  const orig = useRefAD(initial.email);
  const [form, setForm] = useStateAD(initial);
  const [errors, setErrors] = useStateAD({});
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));
  useEffectAD(() => {
    const fn = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", fn);
    return () => window.removeEventListener("keydown", fn);
  }, [onClose]);
  const save = () => {
    const er = {};
    if (!form.name.trim()) er.name = isDe ? "Erforderlich" : "Required";
    if (!form.email.trim()) er.email = isDe ? "Erforderlich" : "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = isDe ? "Ungültige E-Mail" : "Invalid email";
    else if (form.email.toLowerCase() !== orig.current.toLowerCase() && existingEmails.includes(form.email.toLowerCase())) er.email = isDe ? "Existiert bereits" : "Already exists";
    if (Object.keys(er).length) { setErrors(er); return; }
    onSave(orig.current, { ...form, email: form.email.trim(), name: form.name.trim(), aum: parseFloat(form.aum) || 0 });
  };
  return (
    <div className="adm-modal" onClick={onClose}>
      <div className="adm-modal-card" onClick={(e) => e.stopPropagation()}>
        <div className="adm-modal-h">
          <div>
            <div className="adm-modal-eyebrow">{isDe ? "BETEILIGUNG BEARBEITEN" : "EDIT HOLDING"}</div>
            <div className="adm-modal-title">{form.name}</div>
          </div>
          <button onClick={onClose} className="adm-iconbtn">✕</button>
        </div>
        <div className="adm-form-grid" style={{ padding: 28 }}>
          <FormField label={isDe ? "Bezeichnung" : "Name"} error={errors.name}><input value={form.name} onChange={(e) => set("name", e.target.value)} autoFocus /></FormField>
          <FormField label="E-Mail" error={errors.email}><input value={form.email} onChange={(e) => set("email", e.target.value)} type="email" /></FormField>
          <FormField label={isDe ? "Ansprechpartner" : "Primary contact"}><input value={form.contact || ""} onChange={(e) => set("contact", e.target.value)} /></FormField>
          <FormField label="Telefon"><input value={form.phone || ""} onChange={(e) => set("phone", e.target.value)} /></FormField>
          <FormField label="Adresse" full><input value={form.address || ""} onChange={(e) => set("address", e.target.value)} /></FormField>
          <FormField label="Status">
            <select value={form.status} onChange={(e) => set("status", e.target.value)}>
              {STATUS_OPTIONS.map(s => <option key={s.value} value={s.value}>{statusLabel(s, lang)}</option>)}
            </select>
          </FormField>
          <FormField label={isDe ? "Volumen (EUR)" : "AUM (EUR)"}>
            <input value={form.aum || 0} onChange={(e) => set("aum", e.target.value.replace(/[^0-9.]/g, ""))} inputMode="decimal" />
          </FormField>
        </div>
        <div className="adm-form-foot">
          <button onClick={() => onDelete(orig.current)} className="adm-btn-ghost" style={{ color: "#f87171", borderColor: "rgba(248,113,113,0.3)" }}>{isDe ? "Beteiligung löschen" : "Delete holding"}</button>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={onClose} className="adm-btn-ghost">{isDe ? "Abbrechen" : "Cancel"}</button>
            <button onClick={save} className="adm-btn-primary">{isDe ? "Speichern →" : "Save changes →"}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* =========================================================
   Shared bits
   ========================================================= */
function FormField({ label, error, children, full, hint }) {
  return (
    <label className="adm-field" style={{ gridColumn: full ? "1 / -1" : "auto" }}>
      <div className="adm-field-row">
        <span>{label}</span>
        {error && <span style={{ color: "#f87171" }}>{error}</span>}
      </div>
      {React.Children.map(children, (c) => React.cloneElement(c, {
        className: (c.props.className || "") + " adm-input"
      }))}
      {hint && <div style={{ marginTop: 6, fontSize: 10.5, color: "var(--adm-text-dim)" }}>{hint}</div>}
    </label>
  );
}

function StatusPill({ status, lang }) {
  const m = statusMeta(status, lang);
  return (
    <span className="adm-status" style={{ color: m.color, borderColor: m.color + "55", background: m.color + "18" }}>
      {m.label}
    </span>
  );
}

function Pager({ page, totalPages, onPage, lang }) {
  const isDe = lang === "de";
  const pages = [];
  const s = Math.max(1, page - 2);
  const e = Math.min(totalPages, s + 4);
  for (let i = s; i <= e; i++) pages.push(i);
  return (
    <div className="adm-pager">
      <button disabled={page <= 1} onClick={() => onPage(page - 1)}>{isDe ? "Zurück" : "Previous"}</button>
      {pages.map(p => (
        <button key={p} className={p === page ? "on" : ""} onClick={() => onPage(p)}>{p}</button>
      ))}
      <button disabled={page >= totalPages} onClick={() => onPage(page + 1)}>{isDe ? "Weiter" : "Next"}</button>
    </div>
  );
}

function Hi({ text, q }) {
  if (!q || !q.trim() || !text) return text || "";
  const i = text.toLowerCase().indexOf(q.trim().toLowerCase());
  if (i < 0) return text;
  return (
    <>
      {text.slice(0, i)}
      <mark style={{ background: "rgba(251,191,36,0.35)", color: "#fff", padding: "0 1px" }}>{text.slice(i, i + q.trim().length)}</mark>
      {text.slice(i + q.trim().length)}
    </>
  );
}

function AllPurchases({ lang, users, companies, onCreate, onEdit, onDelete, onSetPay, onPatch, onReseed }) {
  const isDe = lang === "de";
  const [pageSize, setPageSize] = useStateAD(10);
  const [pageNum, setPageNum] = useStateAD(1);
  const [query, setQuery] = useStateAD("");

  const purchases = useMemoAD(() => {
    const list = [];
    users.forEach(u => {
      const lots = getUserLots(u);
      lots.forEach(lot => {
        const co = companies.find(c => c.email === lot.companyEmail);
        if (!co) return;
        const qty = (lot.qty != null && lot.qty !== "") ? lot.qty
          : Math.max(100, Math.round(((parseFloat(co.totalShares) || 1000) * 0.01)));
        const buyPrice = (lot.buyPrice != null && lot.buyPrice !== "") ? parseFloat(lot.buyPrice) : parseFloat(co.buyPrice) || 0;
        list.push({
          lotId: lot.id,
          userEmail: u.email, userName: u.name,
          companyEmail: lot.companyEmail, companyName: co.name, companySymbol: co.symbol,
          qty, buyPrice, status: u.status,
          buyDate: lot.buyDate || null,
          payment: lot.payment || "pending",
          lockUntil: lot.lockUntil || null,
          note: lot.note || "",
        });
      });
    });
    return list;
  }, [users, companies]);

  const filtered = useMemoAD(() => {
    const q = query.trim().toLowerCase();
    return purchases.filter(p => !q
      || p.userName.toLowerCase().includes(q)
      || p.companyName.toLowerCase().includes(q)
      || (p.companySymbol || "").toLowerCase().includes(q));
  }, [purchases, query]);

  useEffectAD(() => { setPageNum(1); }, [query, pageSize]);
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const start = (pageNum - 1) * pageSize;
  const visible = filtered.slice(start, start + pageSize);

  const fmt = (n) => Number(n).toLocaleString("de-DE", { style: "currency", currency: "EUR", minimumFractionDigits: 2, maximumFractionDigits: 2 });

  return (
    <div className="adm-card">
      <div style={{ padding: "24px 28px 0" }}>
        <h2 className="adm-form-h" style={{ marginBottom: 4 }}>{isDe ? "Alle Käufe" : "All purchases"}</h2>
        <p className="adm-form-sub" style={{ marginBottom: 0 }}>{isDe ? "Erfasste Käufe über Kunden und Positionen hinweg." : "Recorded purchases across clients and holdings."}</p>
      </div>
      <div className="adm-tbl-tools">
        <label className="adm-show">
          {isDe ? "Zeige" : "Show"}
          <select value={pageSize} onChange={(e) => setPageSize(parseInt(e.target.value, 10))}>
            <option>5</option><option>10</option><option>25</option><option>50</option>
          </select>
          {isDe ? "Einträge" : "entries"}
        </label>
        <div style={{ flex: 1 }}></div>
        <button className="adm-btn-ghost" onClick={onReseed} title="SAP SE · 01.01.2027">{isDe ? "Demo-Sperre" : "Demo lock"}</button>
        <button className="adm-btn-primary" onClick={onCreate}>+ {isDe ? "Neuer Kauf" : "New purchase"}</button>
        <div className="adm-search">
          <input placeholder={isDe ? "SUCHE:" : "SEARCH:"} value={query} onChange={(e) => setQuery(e.target.value)} />
        </div>
      </div>

      <table className="adm-tbl">
        <thead>
          <tr>
            <th>{isDe ? "KUNDE" : "CLIENT"}</th>
            <th>{isDe ? "POSITION" : "HOLDING"}</th>
            <th style={{ textAlign: "right" }}>{isDe ? "MENGE" : "QUANTITY"}</th>
            <th style={{ textAlign: "right" }}>{isDe ? "EINSTAND" : "BUY PRICE"}</th>
            <th>{isDe ? "KAUFDATUM" : "BUY DATE"}</th>
            <th>{isDe ? "SPERRE" : "LOCK"}</th>
            <th>{isDe ? "ZAHLUNG" : "PAYMENT"}</th>
            <th>STATUS</th>
            <th style={{ textAlign: "center" }}>{isDe ? "AKTIONEN" : "ACTIONS"}</th>
          </tr>
        </thead>
        <tbody>
          {visible.length === 0 ? (
            <tr><td colSpan={9} style={{ padding: "60px 20px", textAlign: "center", color: "#82828d" }}>{isDe ? "Keine Käufe gefunden." : "No purchases found."}</td></tr>
          ) : visible.map(p => (
            <tr key={p.lotId}>
              <td>
                <div style={{ color: "#fff", fontWeight: 500 }}><Hi text={p.userName} q={query} /></div>
                <div style={{ fontSize: 10.5, color: "#82828d" }}>{p.userEmail}</div>
              </td>
              <td>
                <div style={{ color: "#fff", fontWeight: 500 }}><Hi text={p.companyName} q={query} /></div>
                {p.companySymbol && <div style={{ fontSize: 10.5, color: "#82828d", fontFamily: "var(--mono)" }}>{p.companySymbol.toUpperCase()}</div>}
                {p.note && <div style={{ fontSize: 10.5, color: "#fbbf24", maxWidth: 260 }}>{p.note}</div>}
              </td>
              <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#fff" }}>{Number(p.qty).toLocaleString("de-DE")}</td>
              <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#a8a8b1" }}>{fmt(p.buyPrice)}</td>
              <td style={{ fontFamily: "var(--mono)", color: "#a8a8b1", fontSize: 12 }}>{window.fmtDate(p.buyDate)}</td>
              <td>
                <input type="date" className="adm-input" style={{ width: 138, padding: "3px 6px" }} value={p.lockUntil || ""}
                  onChange={(e) => onPatch(p, { lockUntil: e.target.value || null })} />
              </td>
              <td><window.PayBadge state={p.payment} lang={lang} onToggle={(s) => onSetPay(p, s)} /></td>
              <td>
                <span style={{ color: p.status === "verified" ? "#34d399" : "#fbbf24", fontWeight: 500 }}>
                  {p.status === "verified" ? (isDe ? "Aktiv" : "Active") : (isDe ? "Prüfung" : "Pending")}
                </span>
              </td>
              <td>
                <div className="adm-actions" style={{ justifyContent: "center" }}>
                  <button className="adm-iconbtn" onClick={() => onEdit(p)} title={isDe ? "Bearbeiten" : "Edit"}><IconEdit /></button>
                  <button className="adm-iconbtn danger" onClick={() => onDelete(p)} title={isDe ? "Löschen" : "Delete"}><IconTrash /></button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      <div className="adm-tbl-foot">
        <div style={{ color: "#82828d", fontSize: 12.5 }}>
          {isDe ? "Zeilen" : "Showing"} {filtered.length === 0 ? 0 : start + 1}–{Math.min(start + pageSize, filtered.length)} {isDe ? "von" : "of"} {filtered.length}
          {purchases.length !== filtered.length && <span style={{ color: "#5d5d67" }}> ({isDe ? "gefiltert aus" : "filtered from"} {purchases.length})</span>}
        </div>
        <Pager page={pageNum} totalPages={totalPages} onPage={setPageNum} lang={lang} />
      </div>
    </div>
  );
}

function PurchaseForm({ lang, mode, initial, users, companies, onCancel, onSave }) {
  const isDe = lang === "de";
  const [form, setForm] = useStateAD({
    userEmail: initial?.userEmail || "",
    companyEmail: initial?.companyEmail || "",
    qty: initial?.qty != null ? String(initial.qty) : "",
    buyPrice: initial?.buyPrice != null ? String(initial.buyPrice) : "",
    buyDate: initial?.buyDate || new Date().toISOString().slice(0, 10),
    payment: initial?.payment || "pending",
    lockUntil: initial?.lockUntil || "",
    note: initial?.note || "",
  });
  const [errors, setErrors] = useStateAD({});
  const set = (k, v) => { setForm(p => ({ ...p, [k]: v })); setErrors(e => ({ ...e, [k]: undefined })); };

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.userEmail) er.userEmail = isDe ? "Erforderlich" : "Required";
    if (!form.companyEmail) er.companyEmail = isDe ? "Erforderlich" : "Required";
    const q = parseFloat(form.qty);
    if (!q || q <= 0) er.qty = isDe ? "Gültige Menge eingeben" : "Enter a valid quantity";
    if (Object.keys(er).length) { setErrors(er); return; }
    const bp = form.buyPrice ? parseFloat(form.buyPrice) : null;
    onSave({ userEmail: form.userEmail, companyEmail: form.companyEmail, qty: q, buyPrice: bp, buyDate: form.buyDate || null, payment: form.payment, lockUntil: form.lockUntil || null, note: form.note });
  };

  const selectedCo = companies.find(c => c.email === form.companyEmail);
  const defaultBuy = selectedCo ? selectedCo.buyPrice : "";

  return (
    <form onSubmit={submit} className="adm-card" style={{ padding: 28 }}>
      <div className="adm-form-h">{mode === "edit" ? (isDe ? "Kauf bearbeiten" : "Edit purchase") : (isDe ? "Kauf erfassen" : "Create a purchase")}</div>
      <p className="adm-form-sub">
        {isDe
          ? "Füllen Sie die Pflichtfelder, um den Kauf zu " + (mode === "edit" ? "aktualisieren" : "erfassen") + ". Dieselbe Position kann mehrfach mit unterschiedlichem Einstand erfasst werden — jedes Los erscheint im Bericht."
          : "Please fill up the required fields to " + (mode === "edit" ? "update this" : "create a") + " purchase. The same holding can be added multiple times with different buy prices — every lot appears on the report."}
      </p>

      <FormSection icon="cart" title={isDe ? "Kaufdetails" : "Purchase details"} />
      <div className="adm-form-grid">
        <FormField label={isDe ? "Kunde" : "Client"} error={errors.userEmail}>
          <select value={form.userEmail} onChange={(e) => set("userEmail", e.target.value)}>
            <option value="">— {isDe ? "Kunde wählen" : "Select client"} —</option>
            {users.map(u => <option key={u.email} value={u.email}>{u.name} · {u.email}</option>)}
          </select>
        </FormField>
        <FormField label={isDe ? "Position" : "Holding"} error={errors.companyEmail}>
          <select value={form.companyEmail} onChange={(e) => set("companyEmail", e.target.value)}>
            <option value="">— {isDe ? "Position wählen" : "Select holding"} —</option>
            {companies.map(c => <option key={c.email} value={c.email}>{c.name}{c.symbol ? ` · ${c.symbol.toUpperCase()}` : ""}</option>)}
          </select>
        </FormField>
        <FormField label={isDe ? "Menge" : "Quantity"} error={errors.qty}>
          <input value={form.qty} onChange={(e) => set("qty", e.target.value.replace(/[^0-9.]/g, ""))} placeholder="100" inputMode="decimal" />
        </FormField>
        <FormField label={isDe ? "Einstand (je Anteil)" : "Buy price (per share)"} hint={defaultBuy ? (isDe ? `Leer lassen für Standard der Position (${defaultBuy})` : `Leave blank to use default (${defaultBuy})`) : (isDe ? "Optional" : "Optional override")}>
          <input value={form.buyPrice} onChange={(e) => set("buyPrice", e.target.value.replace(/[^0-9.]/g, ""))} placeholder={defaultBuy ? String(defaultBuy) : "0,00"} inputMode="decimal" />
        </FormField>
        <FormField label={isDe ? "Kaufdatum" : "Purchase date"} hint={isDe ? "Tag des Kaufs" : "Day of purchase"}>
          <input type="date" value={form.buyDate} onChange={(e) => set("buyDate", e.target.value)} />
        </FormField>
        <FormField label={isDe ? "Verkaufssperre bis" : "Sale lock until"} hint={isDe ? "Kein Verkauf vor diesem Datum" : "No sale before this date"}>
          <input type="date" value={form.lockUntil} onChange={(e) => set("lockUntil", e.target.value)} />
        </FormField>
        <FormField label={isDe ? "Hinweis (Kunde)" : "Note (client)"} hint={isDe ? "Erscheint beim Kunden" : "Shown to the client"} full>
          <input value={form.note} onChange={(e) => set("note", e.target.value)} placeholder={isDe ? "z. B. Verkaufssperre bis 01.01.2027 (Haltefrist)." : "e.g. sale lock until 2027-01-01 (holding period)."} />
        </FormField>
        <FormField label={isDe ? "Zahlungsstatus" : "Payment status"} hint={isDe ? "Sichtbar für den Kunden" : "Visible to the client"}>
          <select value={form.payment} onChange={(e) => set("payment", e.target.value)}>
            <option value="pending">{isDe ? "Ausstehend (gelb)" : "Pending (yellow)"}</option>
            <option value="paid">{isDe ? "Bezahlt (grün)" : "Paid (green)"}</option>
          </select>
        </FormField>
      </div>

      <div className="adm-form-foot">
        <button type="button" className="adm-btn-ghost" onClick={onCancel}>{isDe ? "Abbrechen" : "Cancel"}</button>
        <button type="submit" className="adm-btn-primary">{mode === "edit" ? (isDe ? "Speichern" : "Save changes") : (isDe ? "Erfassen" : "Submit")}</button>
      </div>
    </form>
  );
}

function AdminProfilePage({ lang, onSaved, onCancel }) {
  const isDe = lang === "de";
  const KEY = "aur.admin.profile.v1";
  const load = () => {
    try { const raw = localStorage.getItem(KEY); if (raw) return JSON.parse(raw); } catch (_) {}
    return { firstName: "Betrieb", lastName: "Desk", email: "ops@aurevon.de", password: "aurevon" };
  };
  const [form, setForm] = useStateAD(load);
  const [pw, setPw] = useStateAD("");
  const [pw2, setPw2] = useStateAD("");
  const [errors, setErrors] = useStateAD({});
  const set = (k, v) => { setForm(p => ({ ...p, [k]: v })); setErrors(e => ({ ...e, [k]: undefined })); };

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.firstName.trim()) er.firstName = isDe ? "Erforderlich" : "Required";
    if (!form.email.trim() || !/\S+@\S+\.\S+/.test(form.email)) er.email = isDe ? "Gültige E-Mail erforderlich" : "Valid email required";
    if (pw && pw !== pw2) er.pw2 = isDe ? "Passwörter stimmen nicht überein" : "Passwords do not match";
    if (pw && pw.length < 4) er.pw = isDe ? "Min. 4 Zeichen" : "Min 4 characters";
    if (Object.keys(er).length) { setErrors(er); return; }
    const next = { ...form, email: form.email.trim().toLowerCase(), password: pw ? pw : form.password };
    localStorage.setItem(KEY, JSON.stringify(next));
    setForm(next); setPw(""); setPw2("");
    onSaved && onSaved();
  };

  return (
    <form onSubmit={submit} className="adm-card" style={{ padding: 28, maxWidth: 920, margin: "0 auto" }}>
      <div className="adm-form-h">{isDe ? "Desk-Profil" : "Admin profile"}</div>
      <p className="adm-form-sub">{isDe ? "Persönliche Daten und Passwort ändern." : "Update your personal details and password."}</p>

      <FormSection icon="user" title={isDe ? "Persönliche Angaben" : "Personal information"} />
      <div className="adm-form-grid">
        <FormField label={isDe ? "Vorname" : "First name"} error={errors.firstName}>
          <input value={form.firstName} onChange={(e) => set("firstName", e.target.value)} placeholder="Betrieb" />
        </FormField>
        <FormField label={isDe ? "Nachname" : "Last name"}>
          <input value={form.lastName} onChange={(e) => set("lastName", e.target.value)} placeholder="Desk" />
        </FormField>
        <FormField label="E-Mail" full error={errors.email}>
          <input value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="ops@aurevon.de" />
        </FormField>
      </div>

      <FormSection icon="lock" title={isDe ? "Passwort ändern" : "Change password"} />
      <div className="adm-form-grid">
        <FormField label={isDe ? "Neues Passwort" : "New password"} hint={isDe ? "Leer lassen, um das aktuelle zu behalten." : "Leave blank to keep your current password."} error={errors.pw}>
          <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" />
        </FormField>
        <FormField label={isDe ? "Passwort bestätigen" : "Confirm password"} error={errors.pw2}>
          <input type="password" value={pw2} onChange={(e) => setPw2(e.target.value)} placeholder="••••••••" />
        </FormField>
      </div>

      <div className="adm-form-foot">
        <button type="button" className="adm-btn-ghost" onClick={onCancel}>{isDe ? "Abbrechen" : "Cancel"}</button>
        <button type="submit" className="adm-btn-primary">{isDe ? "Speichern" : "Save changes"}</button>
      </div>
    </form>
  );
}

function ReportPage({ lang, userEmail, users, companies, onBack, onAssign, onSetLot, onRemoveLot, onSetRemarks }) {
  const isDe = lang === "de";
  const user = users.find(u => u.email.toLowerCase() === (userEmail || "").toLowerCase());
  const [addOpen, setAddOpen] = useStateAD(false);
  const [addSel, setAddSel] = useStateAD("");
  const [remarks, setRemarks] = useStateAD(user?.reportRemarks || "");
  React.useEffect(() => { setRemarks(user?.reportRemarks || ""); }, [userEmail]);

  if (!user) {
    return <div className="adm-card" style={{ padding: 32 }}>
      <p style={{ color: "#a8a8b1" }}>{isDe ? "Kein Kunde gewählt." : "No client selected."}</p>
      <button className="adm-btn-ghost" style={{ marginTop: 16 }} onClick={onBack}>← {isDe ? "Zurück" : "Back"}</button>
    </div>;
  }

  const lots = getUserLots(user);
  const rows = lots.map((lot) => {
    const co = companies.find(c => c.email === lot.companyEmail);
    if (!co) return null;
    const buy = (lot.buyPrice != null && lot.buyPrice !== "") ? parseFloat(lot.buyPrice) : (parseFloat(co.buyPrice) || 0);
    const cur = parseFloat(co.currentPrice) || buy;
    const qtyDefault = lot.qty != null && lot.qty !== "" ? lot.qty : Math.max(100, Math.round(((parseFloat(co.totalShares) || 1000) * 0.01)));
    const qty = parseFloat(qtyDefault) || 0;
    const amount = qty * buy;
    const currentAmount = qty * cur;
    const change = buy > 0 ? ((cur - buy) / buy) * 100 : 0;
    return { lotId: lot.id, cEmail: lot.companyEmail, co, qty, buy, cur, amount, currentAmount, change, buyDate: lot.buyDate || null, payment: lot.payment || "pending", lockUntil: lot.lockUntil || null, note: lot.note || "" };
  }).filter(Boolean);

  const subTotal = rows.reduce((s, r) => s + r.amount, 0);
  const totalValue = rows.reduce((s, r) => s + r.currentAmount, 0);
  const totalChange = subTotal > 0 ? ((totalValue - subTotal) / subTotal) * 100 : 0;
  const clientNumber = "AUR-" + (user.email.split("@")[0].toUpperCase().replace(/[^A-Z0-9]/g, "").padEnd(6, "X").slice(0, 6)) + "-" + (user.email.length * 13 % 9999).toString().padStart(4, "0");
  const today = new Date().toISOString().slice(0, 10);
  const currency = user.currency || "EUR";
  const fmtMoney = (n) => `${(n || 0).toLocaleString("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ${currency}`;

  const available = companies;

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
        <button className="adm-btn-ghost" onClick={onBack}>← {isDe ? "Zurück zu Kunden" : "Back to clients"}</button>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="adm-btn-ghost" onClick={() => window.print()}>🖨 {isDe ? "Drucken" : "Print"}</button>
          <button className="adm-btn-primary" onClick={() => {
            const html = document.querySelector(".adm-report-doc")?.outerHTML || "";
            const w = window.open("", "_blank"); if (!w) return;
            w.document.write(`<!doctype html><html lang="de"><head><title>Bericht ${user.name}</title><style>body{font-family:system-ui;padding:40px;color:#111;background:#fff}.adm-report-doc{max-width:900px;margin:0 auto}table{width:100%;border-collapse:collapse}th,td{padding:10px 12px;border-bottom:1px solid #ddd;text-align:left;font-size:13px}th{background:#f5f2ec;text-transform:uppercase;letter-spacing:.08em;font-size:10px;color:#555}.r{text-align:right}.kicker{font-size:10px;letter-spacing:.12em;text-transform:uppercase;color:#666;margin-bottom:6px}h2{margin:0 0 8px}.tot{font-weight:600;background:#f5f2ec}.pos{color:#16a34a}.neg{color:#dc2626}.dis{font-size:10.5px;color:#666;line-height:1.5;margin-top:24px;border-top:1px solid #ddd;padding-top:16px}</style></head><body>${html}</body></html>`);
            w.document.close(); setTimeout(() => w.print(), 300);
          }}>⬇ {isDe ? "Herunterladen" : "Download"}</button>
        </div>
      </div>

      <div className="adm-card adm-report-doc" style={{ padding: 32 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", paddingBottom: 24, borderBottom: "1px solid var(--adm-line)" }}>
          <div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".16em", textTransform: "uppercase", color: "var(--adm-blue)", marginBottom: 6 }}>Aurevon Financial Group · {isDe ? "Kundenbericht" : "Client report"}</div>
            <h2 style={{ color: "#fff", fontSize: 26, margin: 0 }}>{user.name}</h2>
            <div style={{ color: "#a8a8b1", fontSize: 12.5, marginTop: 6, lineHeight: 1.6 }}>
              {user.address || "—"}<br />
              {user.email} · {user.phone || "—"}
              {user.advisor && <><br />{isDe ? "Berater" : "Advisor"}: {user.advisor}</>}
            </div>
          </div>
          <div style={{ textAlign: "right", fontSize: 11.5, color: "#a8a8b1", lineHeight: 1.8 }}>
            <div className="kicker" style={{ marginBottom: 6 }}>{isDe ? "Berichtsdetails" : "Report detail"}</div>
            <div>{isDe ? "Datum" : "Date"}: <span style={{ color: "#fff", fontFamily: "var(--mono)" }}>{today}</span></div>
            <div>{isDe ? "Kundennummer" : "Client number"}: <span style={{ color: "#fff", fontFamily: "var(--mono)" }}>{clientNumber}</span></div>
            <div>{isDe ? "Währung" : "Currency"}: <span style={{ color: "#fff", fontFamily: "var(--mono)" }}>{currency}</span></div>
          </div>
        </div>

        <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div className="kicker">{isDe ? "Positionen" : "Positions"} ({rows.length})</div>
          <button className="adm-link-btn" onClick={() => setAddOpen(v => !v)}>{addOpen ? (isDe ? "Abbrechen" : "Cancel") : (isDe ? "+ Position zuordnen" : "+ Add holding")}</button>
        </div>
        {addOpen && (
          <div style={{ display: "flex", gap: 10, marginTop: 12, padding: 14, background: "rgba(194,160,106,0.08)", border: "1px solid rgba(194,160,106,0.3)" }}>
            <select className="adm-input" value={addSel} onChange={(e) => setAddSel(e.target.value)} style={{ flex: 1 }}>
              <option value="">— {isDe ? "Position zum Zuordnen wählen" : "Select holding to assign"} —</option>
              {available.map(c => <option key={c.email} value={c.email}>{c.name}{c.symbol ? ` · ${c.symbol}` : ""}</option>)}
            </select>
            <button className="adm-btn-primary" disabled={!addSel} onClick={() => { onAssign(user.email, addSel, null); setAddSel(""); setAddOpen(false); }}>{isDe ? "Hinzufügen" : "Add lot"}</button>
          </div>
        )}
        <table className="adm-table" style={{ marginTop: 14 }}>
          <thead>
            <tr>
              <th>{isDe ? "Position" : "Position"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "Menge" : "Quantity"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "Betrag" : "Amount"}</th>
              <th>Symbol</th>
              <th style={{ textAlign: "right" }}>{isDe ? "Veränderung" : "Change"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "Aktueller Wert" : "Current amount"}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && <tr><td colSpan={7} style={{ padding: 24, textAlign: "center", color: "#82828d" }}>{isDe ? "Noch keine Positionen zugeordnet." : "No positions assigned yet."}</td></tr>}
            {rows.map(r => (
              <tr key={r.lotId}>
                <td>
                  <div style={{ color: "#fff", fontWeight: 500 }}>{r.co.name}</div>
                  <div style={{ fontSize: 10.5, color: "#82828d", fontFamily: "var(--mono)" }}>
                    {isDe ? "Einstand" : "Buy"} <input className="adm-input" style={{ width: 80, padding: "2px 6px", display: "inline-block", marginLeft: 4 }} value={r.buy}
                      onChange={(e) => onSetLot(user.email, r.lotId, { buyPrice: parseFloat(e.target.value.replace(/[^0-9.]/g, "")) || 0 })} />
                    {" "}· {isDe ? "Kaufdatum" : "Bought"}{" "}
                    <input type="date" className="adm-input" style={{ width: 130, padding: "2px 6px", display: "inline-block", marginLeft: 2 }}
                      value={r.buyDate || ""} onChange={(e) => onSetLot(user.email, r.lotId, { buyDate: e.target.value || null })} />
                    {" "}· {isDe ? "Kurs" : "Last"} {fmtMoney(r.cur)}
                    <div style={{ marginTop: 4, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                      <window.PayBadge state={r.payment} lang={lang} onToggle={(s) => onSetLot(user.email, r.lotId, { payment: s })} />
                      <span style={{ fontSize: 10.5, color: "#82828d" }}>{isDe ? "Sperre bis" : "Lock until"}</span>
                      <input type="date" className="adm-input" style={{ width: 132, padding: "2px 6px", display: "inline-block" }}
                        value={r.lockUntil || ""} onChange={(e) => onSetLot(user.email, r.lotId, { lockUntil: e.target.value || null })} />
                    </div>
                    <input className="adm-input" style={{ marginTop: 4, padding: "3px 6px", fontSize: 11 }}
                      placeholder={isDe ? "Hinweis zur Veräußerung …" : "Disposal note …"} value={r.note || ""}
                      onChange={(e) => onSetLot(user.email, r.lotId, { note: e.target.value })} />
                  </div>
                </td>
                <td style={{ textAlign: "right" }}>
                  <input className="adm-input" style={{ width: 110, textAlign: "right", padding: "6px 8px" }} value={r.qty}
                    onChange={(e) => onSetLot(user.email, r.lotId, { qty: parseFloat(e.target.value.replace(/[^0-9.]/g, "")) || 0 })} />
                </td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)" }}>{fmtMoney(r.amount)}</td>
                <td style={{ fontFamily: "var(--mono)" }}>{(r.co.symbol || "—").toUpperCase()}</td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: r.change >= 0 ? "#34d399" : "#ef4444" }}>
                  {r.change >= 0 ? "▲" : "▼"} {Math.abs(r.change).toFixed(2).replace(".", ",")} %
                </td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)" }}>{fmtMoney(r.currentAmount)}</td>
                <td style={{ textAlign: "right" }}>
                  <button className="adm-link-btn" onClick={() => { if (window.confirm(`${r.co.name} ${isDe ? "Los entfernen?" : "lot remove?"}`)) onRemoveLot(user.email, r.lotId); }}>✕</button>
                </td>
              </tr>
            ))}
          </tbody>
          {rows.length > 0 && (
            <tfoot>
              <tr style={{ background: "rgba(194,160,106,0.08)" }}>
                <td style={{ color: "#fff", fontWeight: 600 }}>{isDe ? "Summen" : "Totals"}</td>
                <td></td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#fff", fontWeight: 600 }}>{fmtMoney(subTotal)}</td>
                <td></td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: totalChange >= 0 ? "#34d399" : "#ef4444", fontWeight: 600 }}>
                  {totalChange >= 0 ? "▲" : "▼"} {Math.abs(totalChange).toFixed(2).replace(".", ",")} %
                </td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#fff", fontWeight: 600 }}>{fmtMoney(totalValue)}</td>
                <td></td>
              </tr>
            </tfoot>
          )}
        </table>

        <div style={{ marginTop: 28 }}>
          <div className="kicker" style={{ marginBottom: 8 }}>{isDe ? "Anmerkungen" : "Remarks"}</div>
          <textarea rows={3} className="adm-input" placeholder={isDe ? "Interne Notizen zu diesem Bericht…" : "Internal notes about this report…"}
            value={remarks}
            onChange={(e) => setRemarks(e.target.value)}
            onBlur={() => onSetRemarks(user.email, remarks)}
            style={{ width: "100%" }} />
        </div>

        <div style={{ marginTop: 28, paddingTop: 16, borderTop: "1px solid var(--adm-line)", fontSize: 10.5, color: "#82828d", lineHeight: 1.6 }}>
          <strong style={{ color: "#a8a8b1" }}>{isDe ? "Hinweis." : "Disclaimer."}</strong>{" "}
          {isDe
            ? "Diese Aufstellung dient der Information und ist kein Anlagevorschlag, kein Kauf- oder Verkaufsangebot und keine Empfehlung einer bestimmten Transaktion. Positionswerte sind indikativ und können von Abrechnungswerten abweichen. Vergangene Wertentwicklung ist kein Indikator für künftige Ergebnisse. © Aurevon Financial Group GmbH"
            : "This statement is provided for information only and constitutes neither investment advice nor an offer or recommendation of any specific transaction. Position values are indicative and may differ from settlement values. Past performance is not indicative of future results. © Aurevon Financial Group GmbH"}
        </div>
      </div>
    </div>
  );
}

function SiteSettingsPage({ lang, onSaved }) {
  const isDe = lang === "de";
  const [cfg, setCfg] = useStateAD(() => window.loadWaConfig());
  const set = (k, v) => setCfg(c => ({ ...c, [k]: v }));

  const save = (e) => {
    e.preventDefault();
    const clean = { ...cfg, number: String(cfg.number || "").replace(/[^\d]/g, "") };
    localStorage.setItem(window.WA_CONFIG_KEY, JSON.stringify(clean));
    setCfg(clean);
    onSaved && onSaved();
  };

  const reset = () => {
    localStorage.removeItem(window.WA_CONFIG_KEY);
    setCfg(window.loadWaConfig());
    onSaved && onSaved();
  };

  const upload = (file) => {
    if (!file) return;
    if (file.size > 400 * 1024) { alert(isDe ? "Maximal 400 KB." : "400 KB maximum."); return; }
    const r = new FileReader();
    r.onload = () => { set("logoData", String(r.result)); set("logo", "custom"); };
    r.readAsDataURL(file);
  };

  const logoOptions = [
    ["whatsapp", "WhatsApp"],
    ["phone", isDe ? "Telefon" : "Phone"],
    ["chat", isDe ? "Chat" : "Chat"],
    ["custom", isDe ? "Eigenes Bild" : "Custom image"],
  ];

  return (
    <form onSubmit={save} className="adm-card" style={{ padding: 28, maxWidth: 860 }}>
      <div className="adm-form-h">{isDe ? "WhatsApp-Schaltfläche" : "WhatsApp button"}</div>
      <p className="adm-form-sub">
        {isDe
          ? "Nummer, Texte und Symbol der 24/7-Schaltfläche auf der Website. Änderungen erscheinen sofort."
          : "Number, texts and icon of the 24/7 button on the site. Changes appear immediately."}
      </p>

      <FormSection icon="gear" title={isDe ? "Kontakt" : "Contact"} />
      <div className="adm-form-grid">
        <FormField label={isDe ? "WhatsApp-Nummer (international, ohne +)" : "WhatsApp number (international, no +)"} hint={isDe ? "z. B. 497119330800" : "e.g. 497119330800"} full>
          <input value={cfg.number} inputMode="numeric" onChange={(e) => set("number", e.target.value.replace(/[^\d]/g, ""))} />
        </FormField>
        <FormField label={isDe ? "Titel (DE)" : "Title (DE)"}>
          <input value={cfg.titleDe} onChange={(e) => set("titleDe", e.target.value)} />
        </FormField>
        <FormField label={isDe ? "Untertitel (DE)" : "Subtitle (DE)"}>
          <input value={cfg.subDe} onChange={(e) => set("subDe", e.target.value)} />
        </FormField>
        <FormField label="Title (EN)">
          <input value={cfg.titleEn} onChange={(e) => set("titleEn", e.target.value)} />
        </FormField>
        <FormField label="Subtitle (EN)">
          <input value={cfg.subEn} onChange={(e) => set("subEn", e.target.value)} />
        </FormField>
      </div>

      <FormSection icon="gear" title={isDe ? "Symbol" : "Icon"} />
      <div className="adm-form-grid">
        <FormField label={isDe ? "Symbol wählen" : "Choose icon"}>
          <select value={cfg.logo} onChange={(e) => set("logo", e.target.value)}>
            {logoOptions.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        </FormField>
        <FormField label={isDe ? "Eigenes Bild hochladen" : "Upload custom image"} hint={isDe ? "PNG/SVG/JPG, max. 400 KB" : "PNG/SVG/JPG, max 400 KB"}>
          <input type="file" accept="image/*" style={{ padding: 8 }} onChange={(e) => upload(e.target.files && e.target.files[0])} />
        </FormField>
      </div>

      <div style={{ marginTop: 22, display: "flex", alignItems: "center", gap: 14 }}>
        <span style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "#82828d", fontFamily: "var(--mono)" }}>{isDe ? "Vorschau" : "Preview"}</span>
        <span className="wa-preview">
          <span className="wa-fab-icon"><window.WaGlyph kind={cfg.logo} custom={cfg.logoData} /></span>
          <span className="wa-fab-text"><b>{cfg.titleDe}</b><small>{cfg.subDe}</small></span>
        </span>
      </div>

      <div className="adm-form-foot">
        <button type="button" className="adm-btn-ghost" onClick={reset}>{isDe ? "Zurücksetzen" : "Reset"}</button>
        <button type="submit" className="adm-btn-primary">{isDe ? "Speichern" : "Save"}</button>
      </div>
    </form>
  );
}
function TermsPage({ lang }) {
  const isDe = lang === "de";
  return (
    <div className="adm-card" style={{ padding: 32, color: "#a8a8b1", lineHeight: 1.7, fontSize: 13.5 }}>
      <h2 style={{ color: "#fff", fontFamily: "var(--serif)", fontSize: 26, fontWeight: 400, marginBottom: 16 }}>
        {isDe ? "Nutzungsbedingungen der Konsole" : "Console terms of use"}
      </h2>
      <p>
        {isDe
          ? "Der administrative Zugang ist auf Mitarbeiter von Aurevon Financial Group beschränkt. Alle Aktionen werden protokolliert. Änderungen an Kunden- und Positionsdaten werden über den eindeutigen E-Mail-Schlüssel persistiert, damit Suche, Sortierung und Filter nie aus dem Datenbestand laufen."
          : "Administrative access is restricted to Aurevon Financial Group staff. All actions are logged and auditable. Edits to client and holding records are persisted by unique email key so that searches, sorts and filters never desync from the underlying database."}
      </p>
      <p style={{ marginTop: 14 }}>
        {isDe
          ? "Mit der Nutzung erkennen Sie das Desk-Handbuch §4.1–§7.3 an. Berichte nach außen tragen stets den Risikohinweis."
          : "By proceeding you accept the desk handbook §4.1–§7.3. External reports always carry the risk warning."}
      </p>
    </div>
  );
}

/* =========================================================
   Icons (inline SVG)
   ========================================================= */
const sw = { width: 16, height: 16, fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
const IconGrid    = () => <svg viewBox="0 0 24 24" {...sw}><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>;
const IconUsers   = () => <svg viewBox="0 0 24 24" {...sw}><circle cx="9" cy="8" r="3.2"/><path d="M3 20c0-3.3 2.7-6 6-6s6 2.7 6 6"/><circle cx="17" cy="9" r="2.5"/><path d="M21 19c0-2.5-1.8-4.5-4-4.5"/></svg>;
const IconBuilding= () => <svg viewBox="0 0 24 24" {...sw}><rect x="4" y="3" width="16" height="18"/><path d="M9 8h2M13 8h2M9 12h2M13 12h2M9 16h6"/></svg>;
const IconDoc     = () => <svg viewBox="0 0 24 24" {...sw}><path d="M14 3H6v18h12V7l-4-4z"/><path d="M14 3v4h4M9 13h6M9 17h6"/></svg>;
const IconLogout  = () => <svg viewBox="0 0 24 24" {...sw}><path d="M10 4H5v16h5"/><path d="M14 12h7M18 8l4 4-4 4"/></svg>;
const IconUser    = () => <svg viewBox="0 0 24 24" {...sw}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/></svg>;
const IconGear    = () => <svg viewBox="0 0 24 24" {...sw}><circle cx="12" cy="12" r="3.2"/><path d="M12 2.5l1.3 2.6 2.9-.5.6 2.9 2.6 1.3-1.4 2.6 1.4 2.6-2.6 1.3-.6 2.9-2.9-.5L12 21.5l-1.3-2.6-2.9.5-.6-2.9L4.6 15l1.4-2.6L4.6 9.8l2.6-1.3.6-2.9 2.9.5L12 2.5z"/></svg>;
const IconEdit    = () => <svg viewBox="0 0 24 24" {...sw}><path d="M14 4l6 6L8 22H2v-6L14 4z"/></svg>;
const IconTrash   = () => <svg viewBox="0 0 24 24" {...sw}><path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14M10 11v5M14 11v5"/></svg>;
const IconCart    = () => <svg viewBox="0 0 24 24" {...sw}><path d="M3 4h2l2.5 12h11L21 8H6"/><circle cx="9" cy="20" r="1.5"/><circle cx="17" cy="20" r="1.5"/></svg>;

/* Expose storage helpers + seeds for the client app */
window.__atlasStores = {
  USERS_KEY, COMPANIES_KEY, SEED_COMPANIES, SEED_USERS,
  loadStore, saveStore, statusMeta, STATUS_OPTIONS, genTrend,
};
window.AdminApp = AdminApp;
