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

// ═══════════════════════════════════════════════════════════════
// MATRIX HEADER — stats + language toggle
// ═══════════════════════════════════════════════════════════════

function MatrixHeader({ columns, allColumnsCount, profile, products, t, lang, dark, setLang, onOpenSidebar }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";

  const eligibleCount = useMemo(() => {
    let n = 0;
    for (const p of products) {
      if (window.checkEligibility(p, profile).eligible) n++;
    }
    return n;
  }, [products, profile]);

  const profileFilled = window.countProfile ? window.countProfile(profile) : 0;

  const returnBounds = useMemo(() => {
    let lo = Infinity, hi = -Infinity;
    for (const p of products) {
      const r = window.formatRange(p);
      if (!r || r.kind === "multiple") continue;
      lo = Math.min(lo, r.lo); hi = Math.max(hi, r.hi);
    }
    return { lo, hi };
  }, [products]);

  return (
    <div className="r-matrix-header" style={{
      padding: "18px 28px 16px",
      borderBottom: `1px solid ${border}`,
      display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 32,
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
        {onOpenSidebar && (
          <button onClick={onOpenSidebar} className="r-hamburger" aria-label="Open filters" style={{
            width: 40, height: 40,
            background: "transparent", border: `1px solid ${border}`,
            color: text, cursor: "pointer",
            alignItems: "center", justifyContent: "center",
            flexShrink: 0, marginTop: 2,
            padding: 0,
            position: "relative",
          }}>
            <svg width="18" height="12" viewBox="0 0 18 12" fill="none" aria-hidden="true">
              <path d="M0 1h18M0 6h18M0 11h18" stroke="currentColor" strokeWidth="1.4"/>
            </svg>
            {profileFilled > 0 && (
              <span aria-label={`${profileFilled} filters active`} style={{
                position: "absolute", top: -6, right: -6,
                minWidth: 16, height: 16, padding: "0 4px",
                background: "#4866B2", color: "#FFFFFF",
                fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.04em",
                borderRadius: 8,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontVariantNumeric: "tabular-nums",
                border: `2px solid ${dark ? "#1A1817" : "#FAF7F3"}`,
                boxSizing: "content-box",
              }}>{profileFilled}</span>
            )}
          </button>
        )}
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 6 }}>
            {lang === "en" ? "Reurbano · Investor Products" : "Reurbano · Productos de Inversión"}
          </div>
          <div className="r-matrix-title" style={{ fontFamily: "var(--font-display)", fontSize: 30, lineHeight: 1, letterSpacing: "-0.03em", color: text }}>
            {t.matrixTitle}
          </div>
        </div>
      </div>
      <div className="r-hstats" style={{ display: "flex", gap: 28, alignItems: "flex-end" }}>
        <Stat num={eligibleCount} den={products.length} label={t.products_eligible} dark={dark} />
        <Stat num={columns.length} den={allColumnsCount !== columns.length ? allColumnsCount : null} label={t.projects} dark={dark} />
        <Stat text={`${returnBounds.lo}–${returnBounds.hi}%`} label={t.returnsRange} dark={dark} />
        <LangToggle lang={lang} setLang={setLang} dark={dark}/>
      </div>
    </div>
  );
}

function SortControl({ value, setValue, t, dark }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const surface = dark ? "#1A1817" : "#FFFFFF";
  const accent = "#4866B2";
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);

  useEffect(() => {
    const onDown = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("keydown", onKey); };
  }, []);

  const options = [
    ["match", t.sortMatch],
    ["status", t.sortStatus],
    ["stack", t.sortStack],
  ];
  const active = options.find(([v]) => v === value) || options[0];

  return (
    <div ref={rootRef} style={{ position: "relative", alignSelf: "flex-end" }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 4, textAlign: "right" }}>{t.sortBy}</div>
      <button type="button" onClick={() => setOpen(o => !o)} aria-haspopup="listbox" aria-expanded={open} style={{
        height: 32, padding: "0 12px",
        border: `1px solid ${border}`, background: surface, color: text,
        fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase",
        cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8,
      }}>
        <span>{active[1]}</span>
        <svg width="9" height="6" viewBox="0 0 9 6" fill="none" aria-hidden="true">
          <path d="M1 1l3.5 3.5L8 1" stroke="currentColor" strokeWidth="1.3"/>
        </svg>
      </button>
      {open && (
        <div role="listbox" style={{
          position: "absolute", right: 0, top: "calc(100% + 4px)",
          minWidth: "100%", background: surface, border: `1px solid ${border}`,
          boxShadow: "0 8px 24px rgba(0,0,0,0.12)", zIndex: 20,
        }}>
          {options.map(([v, lbl]) => (
            <button key={v} role="option" aria-selected={v === value}
              onClick={() => { setValue(v); setOpen(false); }}
              style={{
                display: "block", width: "100%", textAlign: "left",
                padding: "9px 14px", border: "none",
                background: v === value ? (dark ? "#22201E" : "#F6F2EC") : "transparent",
                color: text, cursor: "pointer",
                fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase",
                borderLeft: v === value ? `2px solid ${accent}` : "2px solid transparent",
              }}>
              {lbl}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function LangToggle({ lang, setLang, dark }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const surface = dark ? "#1A1817" : "#FFFFFF";
  const options = [["EN","en"],["ES","es"]];
  return (
    <div role="group" aria-label="Language" style={{
      display: "inline-flex",
      border: `1px solid ${border}`,
      background: surface,
      height: 32,
      alignSelf: "flex-end",
    }}>
      {options.map(([label, val], i) => {
        const active = val === lang;
        return (
          <button key={val}
            onClick={() => setLang && setLang(val)}
            style={{
              border: "none",
              borderLeft: i === 0 ? "none" : `1px solid ${border}`,
              background: active ? (dark ? "#FAF7F3" : "#393433") : "transparent",
              color: active ? (dark ? "#1A1817" : "#FAF7F3") : text,
              padding: "0 12px",
              fontFamily: "var(--font-mono)",
              fontSize: 10.5,
              letterSpacing: "0.18em",
              cursor: "pointer",
              minWidth: 38,
              transition: "background 150ms, color 150ms",
            }}>
            {label}
          </button>
        );
      })}
    </div>
  );
}

function Stat({ num, den, text, label, dark }) {
  const textColor = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  return (
    <div style={{ textAlign: "right", minWidth: 80 }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 4 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 22, letterSpacing: "-0.02em", color: textColor }} className="r-stat-num">
        {text || <>{num}{den && <span style={{ color: muted, fontSize: 14 }}> / {den}</span>}</>}
      </div>
    </div>
  );
}

window.MatrixHeader = MatrixHeader;
window.SortControl = SortControl;

// ═══════════════════════════════════════════════════════════════
// STATUS RIBBON — tiny band between header and matrix
// ═══════════════════════════════════════════════════════════════
function StatusRibbon({ counts, total, active, setActive, t, dark, sortMode, setSortMode }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const accent = "#4866B2";
  const surface = dark ? "#0D0D0D" : "#FAF7F3";

  const chips = [
    { key: "all", label: t.all, count: total, dot: null },
    { key: "open", label: t.openDeals, count: counts.open || 0, dot: window.STATUS_DOT["open"] },
    { key: "coming-soon", label: t.comingSoon, count: counts["coming-soon"] || 0, dot: window.STATUS_DOT["coming-soon"] },
    { key: "closed", label: t.closed, count: counts.closed || 0, dot: window.STATUS_DOT["closed"] },
  ];

  return (
    <div role="tablist" aria-label="Project status filter" className="r-status-ribbon" style={{
      padding: "10px 28px",
      borderBottom: `1px solid ${border}`,
      background: surface,
      display: "flex", alignItems: "center", gap: 6,
      fontFamily: "var(--font-mono)",
      overflowX: "auto",
    }}>
      <span style={{ fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginRight: 6, flexShrink: 0 }}>
        {t.filterBy}
      </span>
      {chips.map((c, i) => {
        const isActive = active === c.key;
        const disabled = c.key !== "all" && c.count === 0;
        return (
          <button key={c.key}
            role="tab" aria-selected={isActive}
            onClick={() => !disabled && setActive(c.key)}
            disabled={disabled}
            style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              padding: "5px 10px",
              border: `1px solid ${isActive ? (dark ? "#FAF7F3" : "#393433") : border}`,
              background: isActive ? (dark ? "#FAF7F3" : "#393433") : "transparent",
              color: isActive ? (dark ? "#1A1817" : "#FAF7F3") : (disabled ? muted : text),
              fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase",
              cursor: disabled ? "default" : "pointer",
              opacity: disabled ? 0.45 : 1,
              flexShrink: 0,
              transition: "background 160ms, color 160ms, border-color 160ms",
            }}>
            {c.dot && (
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: c.dot, flexShrink: 0, opacity: disabled ? 0.5 : 1 }}/>
            )}
            <span>{c.label}</span>
            <span style={{ color: isActive ? (dark ? "#6B6361" : "#C1C1C1") : muted, fontVariantNumeric: "tabular-nums" }}>{c.count}</span>
          </button>
        );
      })}
      {setSortMode && (
        <div style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
          <span style={{ fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted }}>
            {t.sortBy}
          </span>
          <InlineSort value={sortMode} setValue={setSortMode} t={t} dark={dark}/>
        </div>
      )}
    </div>
  );
}

function InlineSort({ value, setValue, t, dark }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const surface = dark ? "#1A1817" : "#FFFFFF";
  const accent = "#4866B2";
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);

  useEffect(() => {
    const onDown = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("keydown", onKey); };
  }, []);

  const options = [
    ["match", t.sortMatch],
    ["status", t.sortStatus],
    ["stack", t.sortStack],
  ];
  const active = options.find(([v]) => v === value) || options[0];

  return (
    <div ref={rootRef} style={{ position: "relative" }}>
      <button type="button" onClick={() => setOpen(o => !o)} aria-haspopup="listbox" aria-expanded={open} style={{
        padding: "5px 10px",
        border: `1px solid ${border}`, background: surface, color: text,
        fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase",
        cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        <span>{active[1]}</span>
        <svg width="9" height="6" viewBox="0 0 9 6" fill="none" aria-hidden="true">
          <path d="M1 1l3.5 3.5L8 1" stroke="currentColor" strokeWidth="1.3"/>
        </svg>
      </button>
      {open && (
        <div role="listbox" style={{
          position: "absolute", right: 0, top: "calc(100% + 4px)",
          minWidth: "100%", background: surface, border: `1px solid ${border}`,
          boxShadow: "0 8px 24px rgba(0,0,0,0.12)", zIndex: 20,
        }}>
          {options.map(([v, lbl]) => (
            <button key={v} role="option" aria-selected={v === value}
              onClick={() => { setValue(v); setOpen(false); }}
              style={{
                display: "block", width: "100%", textAlign: "left",
                padding: "8px 14px", border: "none",
                background: v === value ? (dark ? "#22201E" : "#F6F2EC") : "transparent",
                color: text, cursor: "pointer",
                fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase",
                borderLeft: v === value ? `2px solid ${accent}` : "2px solid transparent",
                whiteSpace: "nowrap",
              }}>
              {lbl}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

window.StatusRibbon = StatusRibbon;
