/* global React */
const { useState: useStateCA, useEffect: useEffectCA, useMemo: useMemoCA } = React;

/* =========================================================
   ClientApp — read-only client portal.
   Sees ONLY the companies assigned to the logged-in user.
   ========================================================= */
function ClientApp({ lang, userEmail, onLogout }) {
  const stores = window.__atlasStores;
  const [page, setPage] = useStateCA(() => localStorage.getItem("aur.client.page") || new URLSearchParams(window.location.search).get("page") || "dashboard");
  const [users, setUsers] = useStateCA(() => stores.loadStore(stores.USERS_KEY, stores.SEED_USERS));
  const [companies, setCompanies] = useStateCA(() => stores.loadStore(stores.COMPANIES_KEY, stores.SEED_COMPANIES));

  useEffectCA(() => { localStorage.setItem("aur.client.page", page); }, [page]);

  /* Shared state across devices — remote wins, polled. */
  React.useEffect(() => {
    if (!window.remoteGet) return;
    let stop = false;
    let rev = 0;
    const pull = async () => {
      const s = await window.remoteGet();
      if (stop || !s) return;
      if ((s.rev || 0) >= rev) {
        rev = s.rev || 0;
        setUsers(s.users);
        setCompanies(s.companies || []);
        try { stores.saveStore(stores.USERS_KEY, s.users); stores.saveStore(stores.COMPANIES_KEY, s.companies || []); } catch (_) {}
      }
    };
    pull();
    const id = setInterval(pull, 1500);
    const onVis = () => { if (!document.hidden) pull(); };
    document.addEventListener("visibilitychange", onVis);
    window.addEventListener("focus", onVis);
    return () => { stop = true; clearInterval(id); document.removeEventListener("visibilitychange", onVis); window.removeEventListener("focus", onVis); };
  }, []);

  /* Keep the client in lockstep with the admin desk (other tab). */
  React.useEffect(() => {
    const last = { u: "", c: "" };
    const pull = () => {
      try {
        const u = localStorage.getItem(stores.USERS_KEY) || "";
        const c = localStorage.getItem(stores.COMPANIES_KEY) || "";
        if (u && u !== last.u) { last.u = u; setUsers(JSON.parse(u)); }
        if (c && c !== last.c) { last.c = c; setCompanies(JSON.parse(c)); }
      } catch (_) {}
    };
    const id = setInterval(pull, 1200);
    return () => clearInterval(id);
  }, []);

  useEffectCA(() => {
    const onStorage = (e) => {
      if (e.key === stores.USERS_KEY && e.newValue) {
        try { setUsers(JSON.parse(e.newValue)); } catch (_) {}
      } else if (e.key === stores.COMPANIES_KEY && e.newValue) {
        try { setCompanies(JSON.parse(e.newValue)); } catch (_) {}
      }
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  const me = users.find(u => u.email.toLowerCase() === (userEmail || "").toLowerCase()) || { name: lang === "de" ? "Kunde" : "Client", email: userEmail, companies: [] };
  const myCompanyEmails = me.companies || (me.company ? [me.company] : []);
  const myCompanies = companies.filter(c => myCompanyEmails.includes(c.email));

  let body = null;
  if (page === "companies")     body = <MyCompanies companies={myCompanies} lang={lang} />;
  else if (page === "portfolio") body = <MyPortfolio companies={myCompanies} me={me} lang={lang} />;
  else if (page === "terms")    body = <ClTerms lang={lang} />;
  else                          body = <ClientDashboard me={me} companies={myCompanies} go={setPage} lang={lang} />;

  return (
    <div className="adm-shell">
      <ClientSidebar page={page} setPage={setPage} onLogout={onLogout} lang={lang} />
      <div className="adm-main">
        <ClientTopbar page={page} me={me} lang={lang} />
        <div className="adm-body">{body}</div>
      </div>
    </div>
  );
}

function ClientSidebar({ page, setPage, onLogout, lang }) {
  const isDe = lang === "de";
  const [coOpen, setCoOpen] = useStateCA(true);
  const Item = ({ 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>
  );
  const Grid = () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><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 Bld  = () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="3" width="16" height="18"/><path d="M9 8h2M13 8h2M9 12h2M13 12h2M9 16h6"/></svg>;
  const Doc  = () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M14 3H6v18h12V7l-4-4z"/><path d="M14 3v4h4M9 13h6M9 17h6"/></svg>;
  const Out  = () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M10 4H5v16h5"/><path d="M14 12h7M18 8l4 4-4 4"/></svg>;

  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">{lang === "de" ? "Kundenbereich" : "Client area"}</div>
        </div>
      </div>
      <div className="adm-navlabel">NAVIGATION</div>
      <nav className="adm-nav">
        <Item icon={<Grid />} label={isDe ? "Übersicht" : "Dashboard"} active={page === "dashboard"} onClick={() => setPage("dashboard")} />
        <button className={"adm-navgroup" + (page === "companies" || page === "portfolio" ? " on" : "")} onClick={() => setCoOpen(o => !o)}>
          <span className="adm-navicon"><Bld /></span>
          <span style={{ flex: 1, textAlign: "left" }}>{isDe ? "Meine Beteiligungen" : "My holdings"}</span>
          <span className="adm-caret" style={{ transform: coOpen ? "rotate(180deg)" : "" }}>▾</span>
        </button>
        {coOpen && (
          <>
            <Item label={isDe ? "Alle Beteiligungen" : "All holdings"} indent active={page === "companies"} onClick={() => setPage("companies")} />
            <Item label={isDe ? "Mein Portfolio" : "My portfolio"} indent active={page === "portfolio"} onClick={() => setPage("portfolio")} />
          </>
        )}
        <div className="adm-divider"></div>
        <Item icon={<Doc />} label={isDe ? "Nutzungsbedingungen" : "Terms of use"} active={page === "terms"} onClick={() => setPage("terms")} />
        <Item icon={<Out />} label={isDe ? "Abmelden" : "Logout"} onClick={onLogout} />
      </nav>
      <div className="adm-foot">
        <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, color: "#5d5d67" }}>v3.0.0 · {lang === "de" ? "KUNDE" : "CLIENT"}</div>
      </div>
    </aside>
  );
}

function ClientTopbar({ page, me, lang }) {
  const isDe = lang === "de";
  const titles = isDe
    ? { dashboard: "Übersicht", companies: "Meine Beteiligungen", portfolio: "Mein Portfolio", terms: "Nutzungsbedingungen" }
    : { dashboard: "Dashboard", companies: "My holdings", portfolio: "My portfolio", terms: "Terms of use" };
  const subs = isDe
    ? { dashboard: "Willkommen zurück", companies: "Alle Positionen, die Ihrem Depot zugeordnet sind", portfolio: "Ihre Bestände auf einen Blick", terms: "Schreibgeschützter Kundenbereich" }
    : { dashboard: "Welcome back", companies: "All positions assigned to your custody account", portfolio: "Your holdings at a glance", terms: "Read-only client area" };
  const initials = (me.name || "K").split(/\s+/).map(s => s[0]).slice(0, 2).join("").toUpperCase();
  return (
    <div className="adm-topbar">
      <div>
        <h1 className="adm-h1">{titles[page] || page}</h1>
        <div style={{ fontSize: 12.5, color: "#82828d", marginTop: 4 }}>{subs[page]}</div>
      </div>
      <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 10.5, color: "#82828d", fontFamily: "var(--mono)" }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: "#34d399" }}></span>
          XETRA
        </span>
        <div className="lang-toggle" style={{ borderColor: "rgba(255,255,255,0.14)" }}>
          <button onClick={() => window.__setLang("de")} className={isDe ? "on" : ""}>DE</button>
          <button onClick={() => window.__setLang("en")} className={!isDe ? "on" : ""}>EN</button>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontSize: 16.6, color: "#fff", fontWeight: 500, letterSpacing: "-0.01em" }}>{me.name}</div>
          <div style={{ fontSize: 10.5, color: "#82828d", fontFamily: "var(--mono)" }}>{me.email}</div>
          {me.advisor && (
            <div style={{ fontSize: 10.5, lineHeight: 1.4, marginTop: 3, fontFamily: "var(--mono)", color: "#82828d", letterSpacing: "0" }}>
              {isDe ? "BROKER" : "BROKER"}: {me.advisor}{me.advisorDesk ? " · " + me.advisorDesk : ""}
            </div>
          )}
        </div>
        <div className="adm-avatar">{initials}</div>
      </div>
    </div>
  );
}

/* ---------- Dashboard (read-only) ---------- */
function ClientDashboard({ me, companies, go, lang }) {
  const isDe = lang === "de";
  const totalValue = companies.reduce((s, c) => s + (c.totalShares || 0) * (c.sharePrice || 0), 0);
  const totalShares = companies.reduce((s, c) => s + (c.totalShares || 0), 0);
  const fmt = (n) => n.toLocaleString("de-DE", { style: "currency", currency: "EUR", maximumFractionDigits: 0 });
  return (
    <div>
      <div className="adm-grid4">
        <DashStat label={isDe ? "Beteiligungen" : "Holdings"} value={companies.length} delta={isDe ? "zugeordnete Positionen" : "assigned positions"} tone="#c2a06a" onClick={() => go("companies")} />
        <DashStat label={isDe ? "Portfoliowert" : "Portfolio value"} value={fmt(totalValue)} delta={isDe ? "aktuelle Bewertung" : "current valuation"} tone="#34d399" onClick={() => go("portfolio")} />
        <DashStat label={isDe ? "Anteile gesamt" : "Total shares"} value={totalShares.toLocaleString("de-DE")} delta={isDe ? "über alle Positionen" : "across positions"} tone="#8b5cf6" />
        <DashStat label={isDe ? "Status" : "Status"} value={me.status === "verified" ? (isDe ? "VERIFIZIERT" : "VERIFIED") : me.status === "pending" ? (isDe ? "IN PRÜFUNG" : "PENDING") : me.status === "frozen" ? (isDe ? "GESPERRT" : "FROZEN") : "—"} delta={me.role || "Member"} tone="#fbbf24" />
      </div>
      <div className="adm-card" style={{ marginTop: 24 }}>
        <div className="adm-card-h">
          <div className="adm-card-title">{isDe ? "Größte Positionen" : "Top holdings"}</div>
          <span style={{ fontSize: 11.5, color: "#82828d" }}>{isDe ? "schreibgeschützt" : "read-only"}</span>
        </div>
        <ul className="adm-activity">
          {companies.slice(0, 5).map(c => (
            <li key={c.email}>
              <span className="adm-dot"></span>
              <span style={{ flex: 1 }}><b>{c.name}</b> · {(c.symbol || "—").toUpperCase()}</span>
              <span style={{ color: "#34d399", fontFamily: "var(--mono)", fontSize: 11.5 }}>{fmt(c.sharePrice || 0)}</span>
            </li>
          ))}
          {companies.length === 0 && (
            <li style={{ color: "#82828d", justifyContent: "center" }}>
              {isDe ? "Noch keine Beteiligungen zugeordnet. Sprechen Sie Ihren Berater an." : "No holdings assigned yet. Contact your advisor."}
            </li>
          )}
        </ul>
      </div>
    </div>
  );
}
function DashStat({ label, value, delta, tone, onClick }) {
  return (
    <button className="adm-stat" onClick={onClick} style={{ borderLeft: "3px solid " + tone, cursor: onClick ? "pointer" : "default" }}>
      <div className="adm-stat-l">{label}</div>
      <div className="adm-stat-v">{value}</div>
      <div className="adm-stat-d">{delta}</div>
    </button>
  );
}

/* ---------- Holdings table ---------- */
function MyCompanies({ companies, lang }) {
  const isDe = lang === "de";
  const [pageSize, setPageSize] = useStateCA(10);
  const [pageNum, setPageNum] = useStateCA(1);
  const [query, setQuery] = useStateCA("");
  const [sort, setSort] = useStateCA({ k: "name", d: 1 });
  const livePrices = window.useLivePrices(companies.map(c => c.symbol).filter(Boolean));

  const filtered = useMemoCA(() => {
    const q = query.trim().toLowerCase();
    let arr = companies.filter(c => !q || c.name.toLowerCase().includes(q) || (c.symbol || "").toLowerCase().includes(q));
    arr = arr.slice().sort((a, b) => {
      const av = a[sort.k]; const bv = b[sort.k];
      const cmp = typeof av === "number" ? (av - bv) : ((av || "").toString().localeCompare((bv || "").toString(), "de"));
      return cmp * sort.d;
    });
    return arr;
  }, [companies, query, sort]);

  useEffectCA(() => { 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>
          </select>
          {isDe ? "Einträge" : "entries"}
        </label>
        <div style={{ flex: 1 }}></div>
        <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="symbol">SYMBOL</Th>
            <Th k="totalShares" align="right">{isDe ? "ANTEILE" : "TOTAL SHARES"}</Th>
            <Th k="sharePrice" align="right">{isDe ? "KURS (EUR)" : "PRICE (EUR)"}</Th>
            <th style={{ textAlign: "center" }}>TREND</th>
          </tr>
        </thead>
        <tbody>
          {visible.length === 0 ? (
            <tr><td colSpan={5} style={{ padding: "60px 20px", textAlign: "center", color: "#82828d" }}>{isDe ? "Keine Beteiligungen zugeordnet. Sprechen Sie Ihren Berater an." : "No holdings assigned. Contact your advisor."}</td></tr>
          ) : visible.map(c => (
            <tr key={c.email}>
              <td style={{ color: "#fff", fontWeight: 500 }}>{c.name}</td>
              <td style={{ fontFamily: "var(--mono)", color: "#a8a8b1", fontSize: 12 }}>{c.symbol || "—"}</td>
              <td style={{ textAlign: "right", color: "#a8a8b1", fontFamily: "var(--mono)" }}>{(c.totalShares || 0).toLocaleString("de-DE")}</td>
              <td style={{ textAlign: "right", color: "#fff", fontFamily: "var(--mono)", fontWeight: 500 }}>
                {window.fmtEur((livePrices.map[c.symbol] && livePrices.map[c.symbol].price) || c.sharePrice || 0)}
                {livePrices.map[c.symbol] && <span title="live" style={{ color: "#34d399", marginLeft: 4 }}>●</span>}
              </td>
              <td style={{ textAlign: "center" }}><Sparkline points={c.trend || []} /></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>
  );
}

/* ---------- My Portfolio — lots with buy date, live price, P/L, payment state ---------- */
function MyPortfolio({ companies, me, lang }) {
  const isDe = lang === "de";
  const lots = window.getUserLots ? window.getUserLots(me) : [];
  const symbols = lots.map(l => (companies.find(c => c.email === l.companyEmail) || {}).symbol).filter(Boolean);
  const live = window.useLivePrices(symbols);

  const rows = lots.map(l => {
    const co = companies.find(c => c.email === l.companyEmail);
    if (!co) return null;
    const qty = (l.qty != null && l.qty !== "") ? Number(l.qty)
      : Math.max(100, Math.round(((Number(co.totalShares) || 1000) * 0.01)));
    const buy = (l.buyPrice != null && l.buyPrice !== "") ? Number(l.buyPrice) : (Number(co.buyPrice) || 0);
    const quote = live.map[co.symbol];
    const cur = quote && typeof quote.price === "number" ? quote.price : (Number(co.sharePrice) || buy);
    const diff = cur - buy;
    const diffPct = buy > 0 ? (diff / buy) * 100 : 0;
    return { key: l.id, co, qty, buy, cur, diff, diffPct, isLive: !!(quote && quote.price), buyDate: l.buyDate, payment: l.payment || "pending", lockUntil: l.lockUntil || null, note: l.note || "" };
  }).filter(Boolean);

  const totalValue = rows.reduce((s, r) => s + r.qty * r.cur, 0);
  const totalCost = rows.reduce((s, r) => s + r.qty * r.buy, 0);
  const totalPnl = totalValue - totalCost;
  const totalPct = totalCost > 0 ? (totalPnl / totalCost) * 100 : 0;

  return (
    <div>
      <div className="adm-grid4">
        <DashStat label={isDe ? "Depotwert" : "Portfolio value"} value={window.fmtEur(totalValue)} delta={live.live ? (isDe ? "live · XETRA" : "live · XETRA") : (isDe ? "letzter Stand" : "last close")} tone="#34d399" />
        <DashStat label={isDe ? "Einstand gesamt" : "Total cost"} value={window.fmtEur(totalCost)} delta={isDe ? `${rows.length} Positionen` : `${rows.length} positions`} tone="#c2a06a" />
        <DashStat label={isDe ? "G/V gesamt" : "Total P/L"} value={(totalPnl >= 0 ? "+" : "−") + window.fmtEur(Math.abs(totalPnl))} delta={window.fmtPct(totalPct)} tone={window.pnlTone(totalPnl)} />
        <DashStat label={isDe ? "Inhaber" : "Owner"} value={me.name} delta={me.email} tone="#fbbf24" />
      </div>

      <div className="adm-card" style={{ marginTop: 24 }}>
        <div className="adm-card-h">
          <div className="adm-card-title">{isDe ? "Mein Portfolio" : "My portfolio"}</div>
          <span style={{ fontSize: 11.5, color: "#82828d", display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: 9, background: live.live ? "#34d399" : "#5d5d67" }}></span>
            {live.live ? (isDe ? "Live-Kurse" : "live prices") : (isDe ? "Kurse nicht verfügbar" : "prices unavailable")}
          </span>
        </div>
        <table className="adm-tbl">
          <thead>
            <tr>
              <th>{isDe ? "POSITION" : "POSITION"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "MENGE" : "QTY"}</th>
              <th>{isDe ? "KAUFDATUM" : "BOUGHT"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "EINSTAND" : "BUY PRICE"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "LIVE" : "LIVE"}</th>
              <th style={{ textAlign: "right" }}>{isDe ? "G/V" : "P/L"}</th>
              <th>{isDe ? "ZAHLUNG" : "PAYMENT"}</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr><td colSpan={7} style={{ padding: "60px 20px", textAlign: "center", color: "#82828d" }}>{isDe ? "Noch keine Positionen. Nutzen Sie die Suche unten." : "No positions yet. Use the search below."}</td></tr>
            )}
            {rows.map(r => (
              <tr key={r.key}>
                <td>
                  <div style={{ color: "#fff", fontWeight: 500 }}>{r.co.name}</div>
                  <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "#82828d" }}>{(r.co.symbol || "—").toUpperCase()}</div>
                  {r.lockUntil && <span className="lock-chip">🔒 {isDe ? "gesperrt bis" : "locked until"} {window.fmtDate(r.lockUntil)}</span>}
                  {r.note && <div className="pos-note">{r.note}</div>}
                </td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#a8a8b1" }}>{r.qty.toLocaleString("de-DE")}</td>
                <td style={{ fontFamily: "var(--mono)", fontSize: 12, color: "#a8a8b1" }}>{window.fmtDate(r.buyDate)}</td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#a8a8b1" }}>{window.fmtEur(r.buy)}</td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#fff", fontWeight: 500 }}>
                  {window.fmtEur(r.cur)}{r.isLive && <span title="live" style={{ color: "#34d399", marginLeft: 4 }}>●</span>}
                </td>
                <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: window.pnlTone(r.diff), fontWeight: 500, whiteSpace: "nowrap" }}>
                  {r.diff >= 0 ? "▲" : "▼"} {window.fmtEur(Math.abs(r.diff * r.qty))}
                  <div style={{ fontSize: 10.5, opacity: 0.85 }}>{window.fmtPct(r.diffPct)}</div>
                </td>
                <td><window.PayBadge state={r.payment} lang={lang} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {rows.some(r => r.note || r.lockUntil) && (
        <div className="adm-card" style={{ marginTop: 24 }}>
          <div className="adm-card-h">
            <div className="adm-card-title">{isDe ? "Hinweise zur Veräußerung" : "Disposal notices"}</div>
            <span style={{ fontSize: 11.5, color: "#82828d" }}>{isDe ? "vom Desk gesetzt" : "set by the desk"}</span>
          </div>
          <div style={{ padding: "8px 24px 20px" }}>
            {rows.filter(r => r.note || r.lockUntil).map(r => (
              <div key={"n-" + r.key} style={{ padding: "12px 0", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, color: "#fff", fontSize: 13 }}>
                  <b>{r.co.name}</b>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "#82828d" }}>{(r.co.symbol || "").toUpperCase()}</span>
                  {r.lockUntil && <span className="lock-chip">🔒 {isDe ? "kein Verkauf bis" : "no sale before"} {window.fmtDate(r.lockUntil)}</span>}
                </div>
                {r.note && <div className="pos-note" style={{ marginTop: 4 }}>{r.note}</div>}
              </div>
            ))}
          </div>
        </div>
      )}

      <StockSearch lang={lang} companies={companies} />
    </div>
  );
}

/* ---------- Stock search (all symbols, live quotes) ---------- */
function StockSearch({ lang, companies }) {
  const isDe = lang === "de";
  const [q, setQ] = useStateCA("");
  const { results, busy } = window.useSymbolSearch(q);
  const syms = results.map(r => r.symbol);
  const live = window.useLivePrices(syms);
  const held = new Set(companies.map(c => (c.symbol || "").toUpperCase()));
  const base = (sym) => sym.replace(/\.[A-Z]+$/, "");

  return (
    <div className="adm-card" style={{ marginTop: 24 }}>
      <div className="adm-card-h">
        <div className="adm-card-title">{isDe ? "Aktien durchsuchen" : "Search stocks"}</div>
        <span style={{ fontSize: 11.5, color: "#82828d" }}>{isDe ? "live · Yahoo Finance" : "live · Yahoo Finance"}</span>
      </div>
      <div style={{ padding: "16px 24px 0" }}>
        <div className="adm-search" style={{ maxWidth: 420 }}>
          <input placeholder={isDe ? "TICKER ODER NAME · z. B. SAP, Siemens, AAPL" : "TICKER OR NAME · e.g. SAP, Siemens, AAPL"}
            value={q} onChange={(e) => setQ(e.target.value)} autoComplete="off" />
        </div>
        <div style={{ fontSize: 11, color: "#5d5d67", marginTop: 8 }}>
          {busy ? (isDe ? "Suche …" : "Searching …") : q.trim().length < 2 ? (isDe ? "Mindestens 2 Zeichen." : "At least 2 characters.") : ""}
        </div>
      </div>
      <div style={{ padding: "8px 24px 22px" }}>
        {results.length > 0 && (
          <table className="adm-tbl">
            <thead>
              <tr>
                <th>{isDe ? "WERT" : "SECURITY"}</th>
                <th>{isDe ? "BÖRSE" : "EXCHANGE"}</th>
                <th style={{ textAlign: "right" }}>{isDe ? "LIVE" : "LIVE"}</th>
                <th style={{ textAlign: "right" }}>{isDe ? "TAG" : "DAY"}</th>
                <th style={{ textAlign: "right" }}>{isDe ? "STATUS" : "STATUS"}</th>
              </tr>
            </thead>
            <tbody>
              {results.map(r => {
                const quote = live.map[r.symbol];
                const day = quote && quote.prevClose ? ((quote.price - quote.prevClose) / quote.prevClose) * 100 : null;
                const isHeld = held.has(base(r.symbol).toUpperCase());
                return (
                  <tr key={r.symbol}>
                    <td>
                      <div style={{ color: "#fff", fontWeight: 500 }}>{r.name}</div>
                      <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "#82828d" }}>{r.symbol}</div>
                    </td>
                    <td style={{ fontFamily: "var(--mono)", fontSize: 11.5, color: "#82828d" }}>{r.exchange || "—"}</td>
                    <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: "#fff" }}>{quote && quote.price != null ? window.fmtEur(quote.price) : "—"}</td>
                    <td style={{ textAlign: "right", fontFamily: "var(--mono)", color: window.pnlTone(day == null ? 0 : day) }}>{day == null ? "—" : window.fmtPct(day)}</td>
                    <td style={{ textAlign: "right" }}>
                      {isHeld
                        ? <span style={{ fontSize: 10, fontFamily: "var(--mono)", color: "#34d399", border: "1px solid #34d399", padding: "2px 7px" }}>{isDe ? "IM DEPOT" : "HELD"}</span>
                        : <span style={{ fontSize: 10, fontFamily: "var(--mono)", color: "#82828d" }}>{isDe ? "nicht im Depot" : "not held"}</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
function Sparkline({ points }) {
  if (!points || points.length < 2) return <span style={{ color: "#3a3a42" }}>—</span>;
  const w = 100, h = 32;
  const min = Math.min(...points), max = Math.max(...points);
  const span = max - min || 1;
  const xStep = w / (points.length - 1);
  const path = points.map((p, i) => `${i ? "L" : "M"} ${i * xStep},${h - ((p - min) / span) * (h - 4) - 2}`).join(" ");
  return (
    <svg width={w} height={h} style={{ display: "inline-block" }} viewBox={`0 0 ${w} ${h}`}>
      <path d={path} fill="none" stroke="#c2a06a" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

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 ClTerms({ 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" : "Terms of use"}
      </h2>
      <p>
        {isDe
          ? "Dies ist ein schreibgeschützter Kundenbereich. Sie sehen die Positionen, die Ihrem Depot durch Ihren Berater zugeordnet wurden. Änderungen beauftragen Sie bitte über Ihren Ansprechpartner oder den Desk."
          : "This is a read-only client portal. You can view the positions assigned to your account by your advisor. To request changes please contact your relationship manager or the desk."}
      </p>
    </div>
  );
}

window.ClientApp = ClientApp;
