const { useState, useMemo, useEffect, useRef, Fragment } = React;

// ═══════════════════════════════════════════════════════════════
// DETAIL SLIDE-OVER
// ═══════════════════════════════════════════════════════════════
function DetailPanel({ product, onClose, t, lang, dark, shortlist, toggleShortlist, profile, allProducts, onSelectProduct }) {
  const [amount, setAmount] = useState(product?.minimumInvestment.amount || 100000);
  useEffect(() => { if (product) setAmount(product.minimumInvestment.amount); }, [product?.id]);

  // ESC closes the panel
  useEffect(() => {
    if (!product) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [product, onClose]);

  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const faint = dark ? "#5A5654" : "#C1C1C1";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const bg = dark ? "#1A1817" : "#FFFFFF";
  const surface = dark ? "#0D0D0D" : "#FAF7F3";
  const accent = "#4866B2";
  const lime = "#EDFE38";

  const show = !!product;

  // Determine check-size-aware slider max
  const checkMax = { "$50k-$100k": 100000, "$100k-$500k": 500000, "$500k-$1M": 1000000, "$1M+": 2000000 };
  const profileCap = profile && profile.check ? checkMax[profile.check] : null;
  const sliderMax = product
    ? Math.max(product.minimumInvestment.amount * 2, profileCap || 2000000)
    : 2000000;

  const projectedExit = useMemo(() => {
    if (!product) return 0;
    const r = product.targetReturn;
    const [minY, maxY] = product.holdPeriodYears;
    const midY = (minY + maxY) / 2;
    if (r.multiple) return amount * ((r.multiple[0] + r.multiple[1]) / 2);
    if (r.irr) return amount * Math.pow(1 + ((r.irr[0] + r.irr[1]) / 2) / 100, midY);
    if (r.yield) return amount * (1 + ((r.yield[0] + r.yield[1]) / 2) / 100 * midY);
    return amount;
  }, [product, amount]);

  const tier = product ? window.productTier(product) : null;
  const tierIdx = tier ? TIER_ORDER.indexOf(tier) : -1;

  // Eligibility for current product
  const el = useMemo(() => product ? window.checkEligibility(product, profile || {}) : null, [product, profile]);
  const ineligibleWithReasons = el && !el.eligible && !el.unanswered && el.reasons && el.reasons.length > 0;

  // Other tranches in this same project
  const siblings = useMemo(() => {
    if (!product || !allProducts) return [];
    return allProducts.filter(p => p.project === product.project && p.id !== product.id);
  }, [product, allProducts]);

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: "fixed", inset: 0, background: "rgba(13,13,13,0.22)",
        opacity: show ? 1 : 0, pointerEvents: show ? "auto" : "none",
        transition: "opacity 280ms", zIndex: 40,
      }}/>
      {/* Panel */}
      <aside className="r-detail" style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: 440,
        maxWidth: "100vw",
        background: bg, borderLeft: `1px solid ${border}`, color: text,
        transform: show ? "translateX(0)" : "translateX(100%)",
        transition: "transform 320ms cubic-bezier(.4,0,.2,1)",
        zIndex: 50, overflowY: "auto",
        boxShadow: dark ? "none" : "-12px 0 32px rgba(0,0,0,0.08)",
      }}>
        {product && (
          <>
            {/* Header */}
            <div style={{ padding: "22px 28px 16px", borderBottom: `1px solid ${border}`, position: "relative" }}>
              <button onClick={onClose} aria-label="Close" style={{
                position: "absolute", top: 16, right: 16, width: 28, height: 28,
                background: "transparent", border: `1px solid ${border}`, cursor: "pointer",
                color: muted, display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <svg width="12" height="12" viewBox="0 0 12 12"><path d="M2 2l8 8M10 2l-8 8" stroke="currentColor" strokeWidth="1.2"/></svg>
              </button>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
                <span style={{ width: 6, height: 6, background: STATUS_DOT[product.status], borderRadius: "50%" }}/>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted }}>
                  {STATUS_LABEL[product.status][lang]} · {TIER_LABELS[tier].short}
                </span>
                {shortlist && toggleShortlist && (
                  <span style={{ marginLeft: "auto", marginRight: 36 }}>
                    <window.ShortlistStar id={product.id} shortlist={shortlist} toggle={toggleShortlist} dark={dark}/>
                  </span>
                )}
              </div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 24, letterSpacing: "-0.02em", lineHeight: 1.05, color: text }}>
                {product.project}
              </div>
              <div style={{ fontSize: 13, color: muted, marginTop: 4 }}>
                {TIER_LABELS[tier][lang]} · {product.projectCity}
              </div>
            </div>

            {/* Ineligibility reasons — only shown when profile is set AND product is NOT eligible */}
            {ineligibleWithReasons && (
              <div style={{
                padding: "14px 28px", borderBottom: `1px solid ${border}`,
                background: dark ? "rgba(217, 119, 87, 0.08)" : "#FFF4ED",
                borderLeft: `3px solid #D97757`,
              }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "#D97757", marginBottom: 6 }}>
                  {t.whyNotAvailable}
                </div>
                <div style={{ fontSize: 12, color: text, lineHeight: 1.5, marginBottom: 10 }}>
                  {t.whyNotSub}
                </div>
                <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 8 }}>
                  {el.reasons.map((r, i) => {
                    const meta = window.REASON_LABELS[r];
                    if (!meta) return null;
                    return (
                      <li key={r} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                        <span style={{ width: 14, height: 14, flexShrink: 0, border: `1px solid #D97757`, display: "inline-flex", alignItems: "center", justifyContent: "center", marginTop: 2 }}>
                          <svg width="7" height="7" viewBox="0 0 7 7" aria-hidden="true">
                            <path d="M1 1l5 5M6 1l-5 5" stroke="#D97757" strokeWidth="1.2"/>
                          </svg>
                        </span>
                        <div>
                          <div style={{ fontFamily: "var(--font-display)", fontSize: 13, letterSpacing: "-0.005em", color: text, lineHeight: 1.2, marginBottom: 2 }}>
                            {meta[lang]}
                          </div>
                          <div style={{ fontSize: 11.5, color: muted, lineHeight: 1.4 }}>
                            {meta.detail[lang](product, profile || {})}
                          </div>
                        </div>
                      </li>
                    );
                  })}
                </ul>
              </div>
            )}

            {/* Mini stack diagram — clickable to hop between tranches in this project */}
            <div style={{ padding: "16px 28px", borderBottom: `1px solid ${border}`, background: surface }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: muted, marginBottom: 8, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span>{lang === "en" ? "Position in stack" : "Posición en stack"}</span>
                {siblings.length > 0 && (
                  <span style={{ color: muted, textTransform: "none", letterSpacing: 0, fontSize: 10 }}>
                    {siblings.length} {siblings.length === 1 ? (lang === "en" ? "other tranche" : "otro tranche") : (lang === "en" ? "other tranches" : "otros tranches")}
                  </span>
                )}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                {TIER_ORDER.map((tr, i) => {
                  const active = i === tierIdx;
                  const sibling = !active && siblings.find(s => window.productTier(s) === tr);
                  const clickable = !!sibling;
                  const siblingEl = sibling && profile ? window.checkEligibility(sibling, profile) : null;
                  return (
                    <div key={tr}
                      onClick={clickable ? () => onSelectProduct && onSelectProduct(sibling) : undefined}
                      role={clickable ? "button" : undefined}
                      tabIndex={clickable ? 0 : undefined}
                      onKeyDown={clickable ? (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onSelectProduct && onSelectProduct(sibling); } } : undefined}
                      style={{
                        display: "flex", alignItems: "center", gap: 8,
                        padding: "6px 10px",
                        background: active ? accent : (clickable ? (dark ? "#161412" : "#FFFFFF") : "transparent"),
                        border: `1px solid ${active ? accent : border}`,
                        color: active ? "#fff" : (clickable ? text : (dark ? "#403C3A" : faint)),
                        cursor: clickable ? "pointer" : "default",
                        transition: "background 160ms, border-color 160ms",
                      }}>
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", width: 24, opacity: clickable || active ? 1 : 0.5 }}>
                        {String(i+1).padStart(2,"0")}
                      </span>
                      <span style={{ fontSize: 12, letterSpacing: "-0.005em", opacity: clickable || active ? 1 : 0.5 }}>
                        {TIER_LABELS[tr][lang]}
                      </span>
                      {active && <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em" }}>← YOU</span>}
                      {clickable && (
                        <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6 }}>
                          {siblingEl?.eligible && (
                            <svg width="9" height="9" viewBox="0 0 9 9" aria-hidden="true" aria-label="Eligible">
                              <path d="M1.5 4.5 L3.8 6.8 L7.5 2.5" stroke="#2E994B" strokeWidth="1.4" fill="none" strokeLinecap="square"/>
                            </svg>
                          )}
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.08em", color: muted, fontVariantNumeric: "tabular-nums" }}>
                            {window.formatRangeStr(sibling)}
                          </span>
                          <svg width="9" height="9" viewBox="0 0 9 9" aria-hidden="true">
                            <path d="M1 4.5h7M5 1l3.5 3.5L5 8" stroke="currentColor" strokeWidth="1.2" fill="none"/>
                          </svg>
                        </span>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Key metrics */}
            <div style={{ padding: "18px 28px", borderBottom: `1px solid ${border}`, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <Metric label={window.returnKindLabel(product, t)} value={window.formatRangeStr(product)} muted={muted} text={text} lime />
              <Metric label={t.holdPeriod} value={`${product.holdPeriodYears[0]}–${product.holdPeriodYears[1]} ${t.yrs}`} muted={muted} text={text} />
              <Metric label={t.minInvestment} value={window.formatCurrency(product.minimumInvestment.amount)} muted={muted} text={text} />
              <Metric label={t.risk} value={product.riskClass === "debt" ? t.debt : t.equity} muted={muted} text={text} />
            </div>

            {/* Thesis */}
            <div style={{ padding: "18px 28px", borderBottom: `1px solid ${border}` }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 8 }}>
                {t.thesis}
              </div>
              <p style={{ fontSize: 13, color: text, lineHeight: 1.6, margin: 0 }}>
                {product.thesisParagraph}
              </p>
            </div>

            {/* Calculator */}
            <div style={{ padding: "18px 28px", borderBottom: `1px solid ${border}` }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 12 }}>
                {t.calculator}
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                <span style={{ fontSize: 11, color: muted }}>{t.investmentAmount}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: text }}>{window.formatCurrency(amount)}</span>
              </div>
              <input type="range" min={product.minimumInvestment.amount} max={sliderMax}
                step={product.minimumInvestment.amount < 100000 ? 5000 : 25000}
                value={amount} onChange={(e) => setAmount(Number(e.target.value))}
                style={{ width: "100%", accentColor: accent }}/>
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 9, color: muted, marginTop: 4 }}>
                <span>{window.formatCurrency(product.minimumInvestment.amount)}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                  {profileCap && profileCap < 2000000 && (
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 9, letterSpacing: "0.04em", color: accent, textTransform: "uppercase" }}>
                      {t.checkYourCheckCap}
                    </span>
                  )}
                  <span>{window.formatCurrencyShort(sliderMax)}</span>
                </span>
              </div>
              <div style={{ marginTop: 14, padding: "12px 14px", background: surface, border: `1px solid ${border}` }}>
                <div style={{ fontSize: 10.5, color: muted, letterSpacing: "0.04em", marginBottom: 4 }}>{t.projectedExit}</div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: accent, letterSpacing: "-0.02em", lineHeight: 1 }}>
                  {window.formatCurrency(projectedExit)}
                </div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: muted, marginTop: 6 }}>
                  +{window.formatCurrency(projectedExit - amount)} {lang === "en" ? "over" : "en"} {((product.holdPeriodYears[0]+product.holdPeriodYears[1])/2).toFixed(1)} {t.yrs}
                </div>
              </div>
            </div>

            {/* Risk factors */}
            <div style={{ padding: "18px 28px", borderBottom: `1px solid ${border}` }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 10 }}>
                {t.riskFactors}
              </div>
              <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 6 }}>
                {product.riskFactors.map((f, i) => (
                  <li key={i} style={{ fontSize: 12, color: text, lineHeight: 1.5, paddingLeft: 14, position: "relative" }}>
                    <span style={{ position: "absolute", left: 0, top: 7, width: 6, height: 1, background: muted }}/>
                    {f}
                  </li>
                ))}
              </ul>
            </div>

            {/* Next steps — advisor microcard + 3 actions */}
            <div style={{ padding: "18px 28px" }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 12 }}>
                {t.nextSteps}
              </div>

              {/* Advisor microcard */}
              <div style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "12px 14px", marginBottom: 12,
                background: surface, border: `1px solid ${border}`,
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: "50%",
                  background: `linear-gradient(135deg, ${accent} 0%, #6B84C4 100%)`,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  color: "#fff", fontFamily: "var(--font-display)", fontSize: 14, letterSpacing: "-0.01em",
                  flexShrink: 0, position: "relative",
                }}>
                  AR
                  <span style={{
                    position: "absolute", bottom: 0, right: 0,
                    width: 10, height: 10, borderRadius: "50%",
                    background: "#2E994B", border: `2px solid ${surface}`,
                  }}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 13, letterSpacing: "-0.005em", color: text, lineHeight: 1.2 }}>
                    {t.advisorName}
                  </div>
                  <div style={{ fontSize: 10.5, color: muted, marginTop: 2 }}>
                    {t.advisorRole} · {t.advisorOnline}
                  </div>
                </div>
              </div>

              {/* Primary action */}
              <button style={{
                width: "100%", padding: "12px 16px", background: accent, color: "#fff",
                border: "none", fontFamily: "var(--font-body)", fontSize: 13, letterSpacing: "0.02em", cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "center", gap: 8, marginBottom: 8,
              }}>
                {t.bookReview}
                <svg width="12" height="12" viewBox="0 0 12 12"><path d="M1 6h10M7 2l4 4-4 4" stroke="currentColor" strokeWidth="1.4" fill="none"/></svg>
              </button>

              {/* Secondary actions */}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
                <button style={{
                  padding: "10px 10px", background: "transparent", color: text,
                  border: `1px solid ${border}`, fontFamily: "var(--font-body)", fontSize: 11.5,
                  letterSpacing: "0.01em", cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
                }}>
                  <svg width="11" height="11" viewBox="0 0 11 11" aria-hidden="true">
                    <rect x="1" y="2.5" width="9" height="6.5" stroke="currentColor" strokeWidth="1" fill="none"/>
                    <path d="M1 2.5 L5.5 6 L10 2.5" stroke="currentColor" strokeWidth="1" fill="none"/>
                  </svg>
                  {t.emailTermSheet}
                </button>
                <button style={{
                  padding: "10px 10px", background: "transparent", color: text,
                  border: `1px solid ${border}`, fontFamily: "var(--font-body)", fontSize: 11.5,
                  letterSpacing: "0.01em", cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
                }}>
                  <svg width="11" height="11" viewBox="0 0 11 11" aria-hidden="true">
                    <circle cx="3" cy="3" r="1.5" stroke="currentColor" strokeWidth="1" fill="none"/>
                    <circle cx="8.5" cy="2.5" r="1.5" stroke="currentColor" strokeWidth="1" fill="none"/>
                    <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" strokeWidth="1" fill="none"/>
                    <path d="M4.2 3.5L7.3 2.8M4.2 5.5L7.3 7.8" stroke="currentColor" strokeWidth="1" fill="none"/>
                  </svg>
                  {t.shareWithAdvisor}
                </button>
              </div>

              <div style={{ fontSize: 10, color: muted, marginTop: 12, lineHeight: 1.5, textAlign: "center" }}>
                {t.disclaimer}
              </div>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

function Metric({ label, value, muted, text, lime }) {
  return (
    <div>
      <div style={{ fontSize: 10, color: muted, letterSpacing: "0.04em", marginBottom: 3 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 17, color: text, letterSpacing: "-0.01em", lineHeight: 1 }}>
        {value}
      </div>
    </div>
  );
}

window.DetailPanel = DetailPanel;
