/* global React */
/* Live market data — quotes + symbol search through the local /api proxy
   (server.js → Yahoo Finance, 30 s cache). Falls back to the static book. */
const { useState: useStateLV, useEffect: useEffectLV, useRef: useRefLV, useMemo: useMemoLV } = React;

const LIVE_REFRESH_MS = 20000;

function yahooTicker(symbol) {
  const s = String(symbol || "").trim().toUpperCase();
  if (!s) return "";
  return s.includes(".") ? s : s + ".DE";
}

const FALLBACK_BOOK = [
  ["SAP", "SAP SE"], ["SIE", "Siemens AG"], ["ALV", "Allianz SE"], ["DTE", "Deutsche Telekom AG"],
  ["MUV2", "Münchener Rück AG"], ["BAS", "BASF SE"], ["BMW", "BMW AG"], ["ADS", "adidas AG"],
  ["IFX", "Infineon Technologies AG"], ["RWE", "RWE AG"], ["MBG", "Mercedes-Benz Group AG"],
  ["VOW3", "Volkswagen AG Vz."], ["DBK", "Deutsche Bank AG"], ["CBK", "Commerzbank AG"],
  ["HNR1", "Hannover Rück SE"], ["FRE", "Fresenius SE"], ["QIA", "QIAGEN NV"],
  ["SY1", "Symrise AG"], ["SHL", "Siemens Healthineers AG"], ["ZAL", "Zalando SE"],
  ["PUM", "Puma SE"], ["HEI", "Heidelberg Materials AG"], ["MTX", "MTU Aero Engines AG"],
  ["AIR", "Airbus SE"], ["RHM", "Rheinmetall AG"], ["ENR", "Siemens Energy AG"],
  ["BAYN", "Bayer AG"], ["MRK", "Merck KGaA"], ["CON", "Continental AG"], ["LHA", "Lufthansa AG"],
  ["AAPL", "Apple Inc."], ["MSFT", "Microsoft Corp."], ["NVDA", "NVIDIA Corp."], ["GOOGL", "Alphabet Inc."],
  ["AMZN", "Amazon.com Inc."], ["META", "Meta Platforms Inc."], ["TSLA", "Tesla Inc."], ["BRK-B", "Berkshire Hathaway B"],
  ["JPM", "JPMorgan Chase & Co."], ["V", "Visa Inc."], ["XOM", "Exxon Mobil Corp."], ["KO", "Coca-Cola Co."],
].map(([symbol, name]) => ({ symbol, name, exchange: "", type: "EQUITY" }));

const quoteCache = new Map();

/* Netlify CDN proxy paths (used when the /api function is not deployed). */
const Y_PROXY = "/_y";
const Y_DIRECT = "https://query1.finance.yahoo.com";

async function fetchJson(paths) {
  let last;
  for (const p of paths) {
    try {
      const r = await fetch(p, { cache: "no-store" });
      if (!r.ok) throw new Error("HTTP " + r.status);
      return await r.json();
    } catch (e) { last = e; }
  }
  throw last || new Error("fetch failed");
}

function readQuoteCache(symbols) {
  const out = {};
  symbols.forEach(s => { const c = quoteCache.get(s); if (c) out[s] = c; });
  return out;
}

/* Prices keyed by the raw company symbol. */
function useLivePrices(symbols) {
  const key = useMemoLV(() => symbols.map(s => String(s || "")).filter(Boolean).sort().join(","), [symbols.join(",")]);
  const list = useMemoLV(() => key ? key.split(",") : [], [key]);
  const [state, setState] = useStateLV(() => ({ map: readQuoteCache(list), live: false, at: 0 }));

  useEffectLV(() => {
    if (!list.length) return;
    let cancelled = false;
    const load = async () => {
      const tickers = list.map(yahooTicker);
      const map = {};
      const put = (sym, q) => {
        if (!q || typeof q.price !== "number") return;
        const rec = { price: q.price, prevClose: q.prevClose, currency: q.currency, time: q.time };
        quoteCache.set(sym, rec);
        map[sym] = rec;
      };
      try {
        const j = await fetchJson(["/api/quote?symbols=" + encodeURIComponent(tickers.join(","))]);
        list.forEach((sym) => {
          const q = j.quotes && j.quotes[yahooTicker(sym)];
          put(sym, q && typeof q.price === "number" ? q : null);
        });
      } catch (_) {
        await Promise.all(list.map(async (sym) => {
          const t = yahooTicker(sym);
          const qs = "?interval=1d&range=5d";
          try {
            const j = await fetchJson([Y_PROXY + "/chart/" + encodeURIComponent(t) + qs, Y_DIRECT + "/v8/finance/chart/" + encodeURIComponent(t) + qs]);
            const meta = j?.chart?.result?.[0]?.meta;
            if (meta && typeof meta.regularMarketPrice === "number") {
              const prev = meta.chartPreviousClose ?? meta.previousClose ?? null;
              put(sym, { price: meta.regularMarketPrice, prevClose: typeof prev === "number" ? prev : null, currency: meta.currency, time: Date.now() });
            }
          } catch (_) {}
        }));
      }
      if (cancelled) return;
      setState({ map, live: Object.keys(map).length > 0, at: Date.now() });
    };
    load();
    const id = setInterval(load, LIVE_REFRESH_MS);
    return () => { cancelled = true; clearInterval(id); };
  }, [key]);

  return state;
}

/* Symbol search — local instant hits, remote Yahoo search fills in. */
function useSymbolSearch(query) {
  const [remote, setRemote] = useStateLV([]);
  const [busy, setBusy] = useStateLV(false);

  useEffectLV(() => {
    const q = query.trim();
    if (q.length < 2) { setRemote([]); return; }
    let cancelled = false;
    setBusy(true);
    const id = setTimeout(async () => {
      try {
        const qs = "?q=" + encodeURIComponent(q) + "&quotesCount=15&newsCount=0";
        const j = await fetchJson(["/api/search?q=" + encodeURIComponent(q), Y_PROXY + "/search" + qs, Y_DIRECT + "/v1/finance/search" + qs]);
        const list = (j.quotes || [])
          .filter(x => x.symbol && ["EQUITY", "ETF", "INDEX"].includes(x.quoteType))
          .map(x => ({ symbol: x.symbol, name: x.shortname || x.longname || x.symbol, exchange: x.exchange || "", type: x.quoteType }));
        if (!cancelled) setRemote(list.slice(0, 12));
      } catch (_) {
        if (!cancelled) setRemote([]);
      } finally {
        if (!cancelled) setBusy(false);
      }
    }, 250);
    return () => { cancelled = true; clearTimeout(id); };
  }, [query]);

  const local = useMemoLV(() => {
    const q = query.trim().toLowerCase();
    if (!q) return [];
    return FALLBACK_BOOK.filter(x => x.symbol.toLowerCase().includes(q) || x.name.toLowerCase().includes(q));
  }, [query]);

  const merged = [];
  const seen = new Set();
  [...local, ...remote].forEach((x) => {
    if (!x || !x.symbol || seen.has(x.symbol)) return;
    seen.add(x.symbol);
    merged.push(x);
  });
  return { results: merged.slice(0, 12), busy };
}

window.yahooTicker = yahooTicker;
window.useLivePrices = useLivePrices;
window.useSymbolSearch = useSymbolSearch;
window.FALLBACK_BOOK = FALLBACK_BOOK;

/* ---------- formatting ---------- */
function fmtEur(n, digits) {
  if (n == null || isNaN(n)) return "—";
  return Number(n).toLocaleString("de-DE", {
    style: "currency", currency: "EUR",
    minimumFractionDigits: digits == null ? 2 : digits,
    maximumFractionDigits: digits == null ? 2 : digits,
  });
}
function fmtPct(n) {
  if (n == null || isNaN(n)) return "—";
  return (n >= 0 ? "+" : "−") + Math.abs(n).toFixed(2).replace(".", ",") + " %";
}
function pnlTone(n) {
  if (n > 0) return "#34d399";
  if (n < 0) return "#ef4444";
  return "#a8a8b1";
}
function fmtDate(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" });
}
window.fmtEur = fmtEur;
window.fmtPct = fmtPct;
window.pnlTone = pnlTone;
window.fmtDate = fmtDate;

/* ---------- payment badge ---------- */
function PayBadge({ state, lang, onToggle }) {
  const isDe = lang === "de";
  const paid = state === "paid";
  const color = paid ? "#34d399" : "#fbbf24";
  const bg = paid ? "rgba(52,211,153,0.12)" : "rgba(251,191,36,0.12)";
  const label = paid ? (isDe ? "Bezahlt" : "Paid") : (isDe ? "Ausstehend" : "Pending");
  const style = {
    display: "inline-flex", alignItems: "center", gap: 6,
    padding: "3px 9px", border: "1px solid " + color, background: bg, color: color,
    fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.06em", textTransform: "uppercase",
  };
  if (!onToggle) return <span style={style}><span style={{ width: 5, height: 5, borderRadius: 9, background: color }}></span>{label}</span>;
  return (
    <button style={style} title={isDe ? "Status wechseln" : "Toggle status"} onClick={() => onToggle(paid ? "pending" : "paid")}>
      <span style={{ width: 5, height: 5, borderRadius: 9, background: color }}></span>{label}
    </button>
  );
}
window.PayBadge = PayBadge;

/* Market tape: Yahoo trending + day gainers (via /api/tape). */
function useTape() {
  const [state, setState] = useStateLV({ items: [], at: 0 });
  useEffectLV(() => {
    let cancelled = false;
    const load = async () => {
      try {
        const j = await fetchJson(["/api/tape"]);
        if (!cancelled && Array.isArray(j.items) && j.items.length) setState({ items: j.items, at: j.at || Date.now() });
        if (j.items && j.items.length) return;
      } catch (_) {}
      try {
        const [tr, gn] = await Promise.all([
          fetchJson([Y_PROXY + "/trending", Y_DIRECT + "/v1/finance/trending/US?count=10"]).catch(() => null),
          fetchJson([Y_PROXY + "/gainers", Y_DIRECT + "/v1/finance/screener/predefined/saved?scrIds=day_gainers&count=8"]).catch(() => null),
        ]);
        const rise = (gn?.finance?.result?.[0]?.quotes || [])
          .filter(q => q.symbol && typeof q.regularMarketPrice === "number")
          .slice(0, 6)
          .map(q => ({ sym: q.symbol, name: q.shortName || q.symbol, price: q.regularMarketPrice, chg: Number(q.regularMarketChangePercent) || 0 }));
        const syms = (tr?.finance?.result?.[0]?.quotes || []).map(q => q.symbol).filter(Boolean).slice(0, 8);
        const items = [];
        await Promise.all(syms.map(async (s) => {
          try {
            const j = await fetchJson([Y_PROXY + "/chart/" + encodeURIComponent(s) + "?interval=1d&range=5d", Y_DIRECT + "/v8/finance/chart/" + encodeURIComponent(s) + "?interval=1d&range=5d"]);
            const meta = j?.chart?.result?.[0]?.meta;
            if (meta && typeof meta.regularMarketPrice === "number") {
              const prev = meta.chartPreviousClose ?? null;
              items.push({ sym: s, name: meta.shortName || s, price: meta.regularMarketPrice, chg: prev ? ((meta.regularMarketPrice - prev) / prev) * 100 : 0 });
            }
          } catch (_) {}
        }));
        const seen = new Set();
        const merged = [...rise, ...items].filter(x => (seen.has(x.sym) ? false : (seen.add(x.sym), true)));
        if (!cancelled && merged.length) setState({ items: merged, at: Date.now() });
      } catch (_) {}
    };
    load();
    const id = setInterval(load, 45000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);
  return state;
}
window.useTape = useTape;