/* global React */
const { useState: useStateCH, useEffect: useEffectCH, useMemo: useMemoCH } = React;

/* =========================================================
   Market data — synthetic but consistent (European tape)
   ========================================================= */
const INDICES = [
  { sym: "DAX",          val: 19421.36, chg: +0.64 },
  { sym: "MDAX",         val: 27318.02, chg: -0.21 },
  { sym: "EURO STOXX 50",val:  4952.18, chg: +0.38 },
  { sym: "SMI",          val: 12104.55, chg: -0.12 },
  { sym: "VIX",          val:    15.04, chg: -1.87 },
  { sym: "BUND 10J",     val:     2.31, chg: +0.03 },
  { sym: "EUR/USD",      val:    1.087, chg: -0.09 },
];

const STOCKS = [
  { sym: "SAP",  name: "SAP SE",                  px: 214.60, chg: +0.72, mcap: "€ 251B", venue: "XETRA",    sector: "Technologie" },
  { sym: "SIE",  name: "Siemens AG",              px: 182.34, chg: -0.28, mcap: "€ 143B", venue: "XETRA",    sector: "Industrie" },
  { sym: "ALV",  name: "Allianz SE",              px: 292.10, chg: +0.41, mcap: "€ 113B", venue: "XETRA",    sector: "Finanzen" },
  { sym: "DTE",  name: "Deutsche Telekom AG",     px:  24.85, chg: +0.19, mcap: "€ 124B", venue: "XETRA",    sector: "Telekom" },
  { sym: "MUV2", name: "Münchener Rück AG",       px: 486.70, chg: +0.66, mcap: "€  66B", venue: "XETRA",    sector: "Finanzen" },
  { sym: "BAS",  name: "BASF SE",                 px:  45.92, chg: -0.54, mcap: "€  41B", venue: "XETRA",    sector: "Chemie" },
  { sym: "BMW",  name: "BMW AG",                  px:  78.44, chg: +0.93, mcap: "€  49B", venue: "XETRA",    sector: "Auto" },
  { sym: "ADS",  name: "adidas AG",               px: 228.30, chg: +1.14, mcap: "€  41B", venue: "XETRA",    sector: "Konsum" },
  { sym: "IFX",  name: "Infineon Technologies AG",px:  31.28, chg: +1.62, mcap: "€  41B", venue: "XETRA",    sector: "Halbleiter" },
  { sym: "RWE",  name: "RWE AG",                  px:  32.76, chg: -0.37, mcap: "€  24B", venue: "XETRA",    sector: "Energie" },
];

window.INDICES = INDICES;
window.STOCKS = STOCKS;

/* =========================================================
   Sparkline — deterministic seed per symbol
   ========================================================= */
function seededRandom(seed) {
  let s = 0;
  for (let i = 0; i < seed.length; i++) s = (s * 31 + seed.charCodeAt(i)) >>> 0;
  return () => {
    s = (s * 1664525 + 1013904223) >>> 0;
    return s / 0xFFFFFFFF;
  };
}
function Sparkline({ seed = "x", up = true, w = 84, h = 24, stroke }) {
  const rng = useMemoCH(() => seededRandom(seed), [seed]);
  const pts = useMemoCH(() => {
    const N = 24;
    const arr = [];
    let v = 50;
    for (let i = 0; i < N; i++) {
      v += (rng() - 0.5) * 8;
      arr.push(v);
    }
    if (up) arr[arr.length - 1] = Math.max(...arr) + 2;
    else arr[arr.length - 1] = Math.min(...arr) - 2;
    return arr;
  }, [seed]);
  const min = Math.min(...pts), max = Math.max(...pts);
  const norm = pts.map((p, i) => [
    (i / (pts.length - 1)) * w,
    h - ((p - min) / (max - min || 1)) * (h - 2) - 1,
  ]);
  const d = "M " + norm.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(" L ");
  const color = stroke || (up ? "var(--gain)" : "var(--loss)");
  return (
    <svg className="spark" width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <path d={d} fill="none" stroke={color} strokeWidth="1.4" />
    </svg>
  );
}
window.Sparkline = Sparkline;

/* =========================================================
   i18n hook
   ========================================================= */
function useT(lang) {
  return (key) => (window.I18N[lang] && window.I18N[lang][key]) || key;
}
window.useT = useT;

/* =========================================================
   Logo
   ========================================================= */
function Logo({ dark }) {
  const t = useT(window.__lang || "de");
  return (
    <a href="#/" className="logo" style={{ color: dark ? "var(--paper-50)" : "var(--ink-950)" }}>
      <span className="logo-mark" style={{
        background: dark ? "var(--paper-50)" : "var(--ink-950)",
        color: dark ? "var(--ink-950)" : "var(--paper-50)",
      }}>AF</span>
      <span className="logo-text">
        Aurevon
        <small style={{ color: dark ? "var(--ink-400)" : "var(--slate-500)" }}>{t("brand_descriptor")}</small>
      </span>
    </a>
  );
}
window.Logo = Logo;

/* =========================================================
   Top utility bar (status, hours, language toggle)
   ========================================================= */
function UtilBar({ lang, setLang }) {
  const t = useT(lang);
  const [now, setNow] = useStateCH(() => new Date());
  useEffectCH(() => {
    const id = setInterval(() => setNow(new Date()), 30000);
    return () => clearInterval(id);
  }, []);
  const fmt = (tz) => new Intl.DateTimeFormat(lang === "de" ? "de-DE" : "en-GB", {
    hour: "2-digit", minute: "2-digit", timeZone: tz, hour12: false,
  }).format(now);
  return (
    <div className="utilbar">
      <div className="wrap">
        <div className="left">
          <span><span className="dot"></span>{lang === "de" ? "Desk geöffnet · 08:00–22:00" : "Desk open · 08:00–22:00"}</span>
          <span className="muted" style={{ color: "var(--ink-400)" }}>STR {fmt("Europe/Berlin")} · FRA {fmt("Europe/Berlin")} · ZRH {fmt("Europe/Zurich")}</span>
        </div>
        <div className="right">
          <div className="lang-toggle" role="group" aria-label="Sprache">
            <button className={lang === "de" ? "on" : ""} onClick={() => setLang("de")}>DE</button>
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
        </div>
      </div>
    </div>
  );
}
window.UtilBar = UtilBar;

/* =========================================================
   Top nav
   ========================================================= */
function NavBar({ lang, route, navigate }) {
  const t = useT(lang);
  const links = [
    { href: "#/vermoegen",   label: t("nav_advisory"),   match: ["/vermoegen"] },
    { href: "#/trading",     label: t("nav_trading"),    match: ["/trading"] },
    { href: "#/planung",     label: t("nav_planning"),   match: ["/planung"] },
    { href: "#/philosophie", label: t("nav_philosophy"), match: ["/philosophie"] },
    { href: "#/analyse",     label: t("nav_analysis"),   match: ["/analyse"] },
    { href: "#/team",        label: t("nav_team"),       match: ["/team"] },
    { href: "#/werte",       label: t("nav_values"),     match: ["/werte"] },
    { href: "#/kontakt",     label: t("nav_contact"),    match: ["/kontakt"] },
  ];
  return (
    <nav className="nav">
      <div className="wrap">
        <Logo />
        <div className="nav-links">
          {links.map((l) => (
            <a key={l.href} href={l.href}
               className={l.match.includes(route) ? "active" : ""}>{l.label}</a>
          ))}
        </div>
        <div className="nav-cta">
          <a href="#/login" className="btn btn-ghost btn-sm"><span className="lbl-long">{t("nav_login")}</span><span className="lbl-short">Login</span></a>
          <a href="#/kontakt" className="btn btn-primary btn-sm">{t("nav_open_account")}</a>
        </div>
      </div>
    </nav>
  );
}
window.NavBar = NavBar;

/* =========================================================
   Live ticker
   ========================================================= */
function Ticker({ lang }) {
  const t = useT(lang);
  const tape = window.useTape ? window.useTape() : { items: [] };
  const live = tape.items && tape.items.length > 0;
  const fmt = (n) => Number(n).toLocaleString(lang === "de" ? "de-DE" : "en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const rows = live
    ? tape.items.map(x => ({ sym: x.sym, name: x.name, val: x.price, chg: x.chg }))
    : INDICES.map(x => ({ sym: x.sym, val: x.val, chg: x.chg }));
  const items = live ? [...rows, ...rows, ...rows] : [...rows, ...rows, ...rows];
  return (
    <div className="ticker" aria-hidden="false">
      <div className="ticker-label">{live ? (lang === "de" ? "TRENDING · TOP-GEWINNER" : "TRENDING · TOP GAINS") : t("ticker_label")}</div>
      <div className="ticker-track">
        {items.map((it, i) => (
          <div className="ticker-item" key={i} title={it.name || it.sym}>
            <span className="sym">{it.sym}</span>
            <span className="val tabnum">{fmt(it.val)}</span>
            <span className={"chg tabnum " + (it.chg >= 0 ? "up" : "dn")}>{it.chg >= 0 ? "▲" : "▼"} {Math.abs(it.chg).toFixed(2)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}
window.Ticker = Ticker;
/* Right-hand market rail — trending + top gainers, Yahoo-style */
function TrendingRail({ lang }) {
  const tape = window.useTape ? window.useTape() : { items: [] };
  const fallback = (window.FALLBACK_BOOK || []).slice(0, 8).map(x => ({ sym: x.symbol, name: x.name, price: 0, chg: 0 }));
  const pool = tape.items && tape.items.length ? tape.items : fallback;
  const live = !!(tape.items && tape.items.length);
  const fmt = (n) => Number(n).toLocaleString(lang === "de" ? "de-DE" : "en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const gainers = live ? pool.filter(x => x.chg > 0).slice(0, 5) : [];
  const trending = pool.slice(0, 8);
  const Row = ({ x }) => (
    <a className="rail-row" href={"https://finance.yahoo.com/quote/" + encodeURIComponent(x.sym)} target="_blank" rel="noopener noreferrer">
      <span className="rail-id">
        <b>{x.sym}</b>
        <small>{x.name && x.name !== x.sym ? x.name : "\u00a0"}</small>
      </span>
      <span className="rail-num">
        <span className="rail-price tabnum">{x.price ? fmt(x.price) : "—"}</span>
        <span className={"tabnum " + (x.chg >= 0 ? "up" : "dn")}>{x.chg >= 0 ? "▲" : "▼"} {Math.abs(x.chg).toFixed(2)}%</span>
      </span>
    </a>
  );
  return (
    <aside className="market-rail">
      <div className="rail-head">
        <span>{lang === "de" ? "MARKT · LIVE" : "MARKET · LIVE"}</span>
        <span className="rail-dot"></span>
      </div>

      {gainers.length > 0 && (
        <>
          <div className="rail-label">{lang === "de" ? "TOP-GEWINNER" : "TOP GAINERS"}</div>
          {gainers.map(x => <Row key={"g-" + x.sym} x={x} />)}
        </>
      )}
      <div className="rail-label">{lang === "de" ? "TRENDING" : "TRENDING"}</div>
      {trending.map(x => <Row key={"t-" + x.sym} x={x} />)}

      <div className="rail-foot">{lang === "de" ? "Daten: Yahoo Finance · 45 s" : "Data: Yahoo Finance · 45 s"}</div>
    </aside>
  );
}
window.TrendingRail = TrendingRail;

/* Docked ticker — sticky under the nav on the site, fixed at the top of the
   login and portal screens so the tape always stays in the same place. */
function TickerDock({ lang, fixed }) {
  return (
    <div className={"ticker-dock" + (fixed ? " fixed" : "")}>
      <Ticker lang={lang} />
    </div>
  );
}
window.TickerDock = TickerDock;

/* =========================================================
   WhatsApp — 24/7 urgent line, fixed bottom-left
   ========================================================= */
/* WhatsApp config — editable by the admin (number, texts, logo). */
const WA_CONFIG_KEY = "aur.wa.config.v1";
const WA_TEXT_DE = "Hallo Aurevon, ich brauche kurzfristig Unterstützung.";
const WA_DEFAULTS = {
  number: "497119330800",
  titleDe: "24/7 erreichbar",
  titleEn: "Reachable 24/7",
  subDe: "WhatsApp · auch bei akutem Bedarf",
  subEn: "WhatsApp · also for urgent matters",
  logo: "whatsapp",
  logoData: "",
};

function loadWaConfig() {
  try {
    const raw = localStorage.getItem(WA_CONFIG_KEY);
    if (raw) return { ...WA_DEFAULTS, ...JSON.parse(raw) };
  } catch (_) {}
  return { ...WA_DEFAULTS };
}
window.WA_CONFIG_KEY = WA_CONFIG_KEY;
window.WA_DEFAULTS = WA_DEFAULTS;
window.loadWaConfig = loadWaConfig;

function useWaConfig() {
  const [cfg, setCfg] = useStateCH(loadWaConfig);
  useEffectCH(() => {
    const pull = () => {
      const next = JSON.stringify(loadWaConfig());
      setCfg(c => (JSON.stringify(c) === next ? c : JSON.parse(next)));
    };
    const id = setInterval(pull, 1500);
    window.addEventListener("storage", pull);
    return () => { clearInterval(id); window.removeEventListener("storage", pull); };
  }, []);
  return cfg;
}

function WaGlyph({ kind, custom }) {
  if (kind === "custom" && custom) return <img src={custom} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: 999 }} />;
  if (kind === "phone") return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
      <path d="M5 3h4l2 5-2.5 1.5a13 13 0 0 0 6 6L16 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 5a2 2 0 0 1 2-2z"/>
    </svg>
  );
  if (kind === "chat") return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round">
      <path d="M4 5h16v11H9l-5 4V5z"/><path d="M8 9h8M8 12h5"/>
    </svg>
  );
  return (
    <svg viewBox="0 0 24 24" width="19" height="19" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.999-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.888 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
  );
}
window.WaGlyph = WaGlyph;

function WhatsAppFab({ lang }) {
  const t = useT(lang);
  const cfg = useWaConfig();
  const text = encodeURIComponent(lang === "de" ? WA_TEXT_DE : "Hello Aurevon, I need support at short notice.");
  const title = (lang === "de" ? cfg.titleDe : cfg.titleEn) || t("wa_title");
  const sub = (lang === "de" ? cfg.subDe : cfg.subEn) || t("wa_sub");
  return (
    <a className="wa-fab" href={"https://wa.me/" + cfg.number + "?text=" + text}
       target="_blank" rel="noopener noreferrer" aria-label={t("wa_aria")}>
      <span className="wa-fab-icon" aria-hidden="true">
        <WaGlyph kind={cfg.logo} custom={cfg.logoData} />
      </span>
      <span className="wa-fab-text">
        <b>{title}</b>
        <small>{sub}</small>
      </span>
    </a>
  );
}
/* legacy block kept for reference */
function WhatsAppFabLegacy({ lang }) {
  const t = useT(lang);
  const text = encodeURIComponent(lang === "de" ? WA_TEXT_DE : "Hello Aurevon, I need support at short notice.");
  return (
    <a className="wa-fab" href={"https://wa.me/" + WA_DEFAULTS.number + "?text=" + text}
       target="_blank" rel="noopener noreferrer" aria-label={t("wa_aria")}>
      <span className="wa-fab-icon" aria-hidden="true">
        <svg viewBox="0 0 24 24" width="19" height="19" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.999-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.888 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
      </span>
      <span className="wa-fab-text">
        <b>{t("wa_title")}</b>
        <small>{t("wa_sub")}</small>
      </span>
    </a>
  );
}
window.WhatsAppFab = WhatsAppFab;

/* =========================================================
   Footer
   ========================================================= */
function Footer({ lang }) {
  const t = useT(lang);
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-brand">
            <Logo dark />
            <p>{lang === "de"
              ? "Unabhängige, honorarbasierte Vermögensverwaltung mit eigenem Trading Desk. Ein Haus, eine Adresse: Stuttgart."
              : "Independent, fee-based wealth management with an in-house trading desk. One house, one address: Stuttgart."}</p>
            <div className="reg-pill">
              <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--gold)" }}></span>
              § 34f GewO · DIHK-Vermittlungsregister
            </div>
          </div>
          <div>
            <h4>{t("footer_offices")}</h4>
            <ul>
              <li>Aurevon Financial Group GmbH</li>
              <li>Königstraße 41</li>
              <li>70173 Stuttgart</li>
              <li>{lang === "de" ? "Mo–Fr 08:00–18:00" : "Mon–Fri 08:00–18:00"}</li>
            </ul>
          </div>
          <div>
            <h4>{t("footer_legal")}</h4>
            <ul>
              <li><a href="#/rechtliches">{t("footer_terms")}</a></li>
              <li><a href="#/rechtliches">{t("footer_privacy")}</a></li>
              <li><a href="#/rechtliches">{t("footer_form")}</a></li>
              <li><a href="#/rechtliches">{t("footer_imprint")}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t("footer_contact")}</h4>
            <ul>
              <li>kontakt@aurevon.de</li>
              <li>+49 711 9330 800</li>
              <li><a href="#/login">{t("nav_login")} →</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div className="legal">
            <strong style={{ color: "var(--paper-50)", display: "block", marginBottom: 8, fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase" }}>{t("footer_risk")}</strong>
            {t("footer_disclaimer")}
          </div>
          <div style={{ textAlign: "right" }}>
            © 2011–2026 Aurevon Financial Group GmbH.<br/>
            <span style={{ color: "var(--ink-500)" }}>{t("footer_rights")}</span>
          </div>
        </div>
      </div>
    </footer>
  );
}
window.Footer = Footer;

/* =========================================================
   Page wrapper for marketing pages
   ========================================================= */
function MarketingShell({ lang, setLang, route, children, showTicker }) {
  window.__lang = lang;
  return (
    <div>
      <UtilBar lang={lang} setLang={setLang || window.__setLang} />
      <NavBar lang={lang} route={route} />
      {showTicker && <TickerDock lang={lang} />}
      <main>{children}</main>
      <Footer lang={lang} />
    </div>
  );
}
window.MarketingShell = MarketingShell;
