// drawer.jsx — detail view as a side drawer.

function StockDrawer({ ticker, onClose, onRemove }) {
  const [quote, setQuote] = React.useState(null);
  const [range, setRange] = React.useState("1D");
  const [confirmingRemove, setConfirmingRemove] = React.useState(false);

  React.useEffect(() => {
    if (!ticker) return undefined;
    let unsub;
    let cancelled = false;
    fetchQuote(ticker).then((q) => {
      if (cancelled) return;
      setQuote({ ...q });
      unsub = subscribeToQuoteUpdates(ticker, (next) => setQuote({ ...next }));
    });
    return () => {
      cancelled = true;
      if (unsub) unsub();
    };
  }, [ticker]);

  React.useEffect(() => {
    if (!ticker) return undefined;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [ticker, onClose]);

  // A fresh ticker — or a close/reopen — always starts out of the confirm state.
  React.useEffect(() => { setConfirmingRemove(false); }, [ticker]);

  if (!ticker) return null;
  const d = quote ? resolveDisplayQuote(quote) : null;
  const direction = d
    ? d.displayChange > 0 ? "up" : d.displayChange < 0 ? "down" : "flat"
    : "flat";
  const sessionKey = d ? d.sessionLabel.toLowerCase().replace(/\s/g, "-") : "";

  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <aside className={"drawer drawer--" + direction} role="dialog" aria-modal="true">
        <button className="drawer__close" onClick={onClose} aria-label="Close">
          <svg viewBox="0 0 14 14" width="12" height="12">
            <path d="M2 2 L12 12 M12 2 L2 12" stroke="currentColor"
                  strokeWidth="1.25" fill="none" strokeLinecap="round" />
          </svg>
        </button>

        {!quote ? (
          <div className="drawer__loading">Loading quote…</div>
        ) : (
          <>
            <header className="drawer__hd">
              <div className="drawer__brand-row">
                <CompanyLogo ticker={quote.ticker} name={quote.name} domain={quote.logoDomain} />
                <div className="drawer__id">
                  <div className="drawer__ticker">{quote.ticker}</div>
                  <div className="drawer__exch">
                    <span>{quote.exchange}</span>
                    <span className="dot-sep">·</span>
                    <span>{quote.currency}</span>
                  </div>
                </div>
              </div>
              <div className="drawer__name">{quote.name}</div>
            </header>

            <section className="drawer__price-section">
              <a
                className="drawer__price-link"
                href={"https://finance.yahoo.com/quote/" + encodeURIComponent(quote.ticker)}
                target="_blank"
                rel="noopener noreferrer"
                title={"Open " + quote.ticker + " on Yahoo Finance"}>
                <span className="drawer__price">
                  {formatPrice(d.displayPrice, quote.currency)}
                </span>
                <svg className="drawer__price-arrow" viewBox="0 0 14 14" width="14" height="14" aria-hidden="true">
                  <path d="M4 10 L10 4 M5 4 H10 V9" stroke="currentColor"
                        strokeWidth="1.25" fill="none"
                        strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </a>
              <div className={"drawer__session drawer__session--" + sessionKey}>
                <span className="drawer__session-dot" />
                {d.sessionLabel}
              </div>
              {d.secondaryLabel && (
                <div className={"drawer__session drawer__session--secondary drawer__session--"
                                + d.secondaryLabel.toLowerCase().replace(/\s/g, "-")}>
                  <span className="drawer__session-dot" />
                  {d.secondaryLabel}
                </div>
              )}
              <div className={"drawer__move drawer__move--" + direction}>
                {formatChange(d.displayChange, quote.currency)}
                <span className="drawer__move-sep"> · </span>
                {formatPercent(d.displayChangePercent)}
              </div>
              <div className="drawer__ts">Updated {d.timestamp || "—"}</div>
            </section>

            <section className="drawer__chart">
              <div className="drawer__chart-tabs" role="tablist">
                {["1D", "5D", "1M", "6M", "YTD", "1Y"].map((r) => (
                  <button
                    key={r}
                    className={"drawer__tab" + (r === range ? " is-active" : "")}
                    onClick={() => setRange(r)}>
                    {r}
                  </button>
                ))}
              </div>
              <MiniChart
                seed={quote.ticker + range}
                direction={direction}
                points={range === "1D" ? 48 : range === "5D" ? 80 : 120}
              />
              <div className="drawer__chart-foot">
                <span>Indicative · not a real chart</span>
              </div>
            </section>

            <section className="drawer__stats">
              <Stat label="Previous close"
                    value={formatPrice(quote.previousClose, quote.currency)} />
              <Stat label="Open" value={formatPrice(quote.open, quote.currency)} />
              <Stat label="Day range" value={quote.dayRange} />
              <Stat label="52-week range" value={quote.range52w} />
              <Stat label="Volume" value={quote.volume} />
              <Stat label="Avg. volume" value={quote.averageVolume} />
              <Stat label="Market cap" value={quote.marketCap} />
              <Stat label="P/E" value={quote.peRatio} />
              <Stat label="EPS" value={quote.eps} />
              <Stat label="Next earnings" value={quote.earningsDate} />
              <Stat label="Exchange" value={quote.exchange} />
              <Stat label="Timezone" value={quote.exchangeTimezoneName} />
            </section>

            <section className="drawer__provider">
              <div className="drawer__provider-row">
                <span>Source session</span>
                <span className="drawer__provider-val">{quote.marketState}</span>
              </div>
              <div className="drawer__provider-row">
                <span>Extended hours</span>
                <span className="drawer__provider-val">
                  {quote.preMarketPrice != null || quote.postMarketPrice != null
                    ? "Available"
                    : "Unavailable"}
                </span>
              </div>
              <div className="drawer__provider-row">
                <span>Last tick</span>
                <span className="drawer__provider-val">{d.timestamp || "—"}</span>
              </div>
            </section>

            <section className="drawer__danger">
              {!confirmingRemove ? (
                <button
                  className="drawer__remove"
                  onClick={() => setConfirmingRemove(true)}>
                  <svg className="drawer__remove-icon" viewBox="0 0 16 16"
                       width="14" height="14" aria-hidden="true">
                    <path d="M2 4h12 M6 4V2.5h4V4 M3.6 4l.7 9a1 1 0 0 0 1 .95h5.4a1 1 0 0 0 1-.95l.7-9 M6.6 6.4v5.2 M9.4 6.4v5.2"
                          stroke="currentColor" strokeWidth="1.1" fill="none"
                          strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  Remove from watchlist
                </button>
              ) : (
                <div className="drawer__confirm" role="alertdialog"
                     aria-label="Confirm remove from watchlist">
                  <div className="drawer__confirm-msg">
                    Remove <strong>{quote.ticker}</strong> from your watchlist?
                  </div>
                  <div className="drawer__confirm-actions">
                    <button className="drawer__confirm-keep"
                            onClick={() => setConfirmingRemove(false)}>
                      Keep
                    </button>
                    <button className="drawer__confirm-go" onClick={onRemove}>
                      Remove
                    </button>
                  </div>
                </div>
              )}
            </section>
          </>
        )}
      </aside>
    </>
  );
}

function Stat({ label, value }) {
  return (
    <div className="stat">
      <div className="stat__label">{label}</div>
      <div className="stat__value">{value ?? "—"}</div>
    </div>
  );
}

// Deterministic sparkline so each ticker/range pair stays stable across re-renders
function MiniChart({ seed, direction, points = 48 }) {
  const path = React.useMemo(() => {
    const W = 1000, H = 220, pad = 8;
    let s = 0;
    for (let i = 0; i < seed.length; i++) s = (s * 31 + seed.charCodeAt(i)) | 0;
    const rnd = () => {
      s = (s * 1664525 + 1013904223) | 0;
      return ((s >>> 0) % 10000) / 10000;
    };
    const ys = [];
    let v = 0.5;
    for (let i = 0; i < points; i++) {
      v += (rnd() - 0.5) * 0.08;
      v = Math.max(0.1, Math.min(0.9, v));
      ys.push(v);
    }
    // Bias the endpoint to match direction so the chart visually agrees with the price move
    const bias = direction === "up" ? -0.18 : direction === "down" ? 0.18 : 0;
    ys[0] = Math.max(0.1, Math.min(0.9, ys[0] + bias));
    const stepX = (W - pad * 2) / (points - 1);
    const toY = (n) => pad + (1 - n) * (H - pad * 2);
    let line = "M " + pad + " " + toY(ys[0]);
    for (let i = 1; i < points; i++) {
      line += " L " + (pad + i * stepX) + " " + toY(ys[i]);
    }
    const fill = line +
      " L " + (W - pad) + " " + (H - pad) +
      " L " + pad + " " + (H - pad) + " Z";
    return { line, fill, last: ys[ys.length - 1], lastX: W - pad };
  }, [seed, points, direction]);

  return (
    <svg className="mini-chart" viewBox="0 0 1000 220" preserveAspectRatio="none">
      <defs>
        <linearGradient id={"g-" + seed} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="currentColor" stopOpacity="0.10" />
          <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={path.fill} fill={"url(#g-" + seed + ")"} />
      <path d={path.line} fill="none" stroke="currentColor" strokeWidth="1.25"
            strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

window.StockDrawer = StockDrawer;
