// Mobile redesign — header + feed.
//
// Header layout matches the v2 design screenshots:
//   row 1: logo · "Opportunities" · spacer · EN/ES seg · USD/MXN seg
//   row 2: three lime filter chips (Residency, Check size, Horizon),
//          each wraps a native <select> for the picker UX
//   row 3: FX rate hint, right-aligned
//   row 4: "N PROJECTS · M FIT YOUR PROFILE" stats bar
//
// No empty state — filters are inline and always visible, so the feed
// always renders cards even with a blank profile.

const { useMemo: _useMemoMF } = React;

function _mfMuted(dark) { return dark ? "#8A827F" : "#6B6361"; }
function _mfBorder(dark) { return dark ? "#2A2825" : "#E2E0DF"; }
function _mfInk(dark) { return dark ? "#FAF7F3" : "#393433"; }
function _mfSurface(dark) { return dark ? "#0D0D0D" : "#FAF7F3"; }

// Segmented two-option toggle (EN/ES, USD/MXN). Matches the design's
// pill-pair where the active option fills with ink and the inactive sits
// inside a 1px outline.
function MobileSegToggle({ value, options, onChange, dark, ariaLabel }) {
  const ink = _mfInk(dark);
  const border = _mfBorder(dark);
  const surface = _mfSurface(dark);
  return (
    <div role="group" aria-label={ariaLabel} style={{
      display: "inline-flex",
      border: `1px solid ${border}`,
    }}>
      {options.map((opt, i) => {
        const active = opt.value === value;
        return (
          <button
            key={opt.value}
            type="button"
            onClick={() => onChange(opt.value)}
            aria-pressed={active}
            style={{
              padding: "5px 8px",
              minWidth: 34,
              background: active ? ink : surface,
              color: active ? surface : ink,
              border: "none",
              cursor: "pointer",
              fontFamily: "var(--font-mono)",
              fontSize: 10.5,
              letterSpacing: "0.12em",
              textTransform: "uppercase",
              borderLeft: i === 0 ? "none" : `1px solid ${border}`,
            }}>
            {opt.label}
          </button>
        );
      })}
    </div>
  );
}

// Lime filter chip wrapping a native <select>. The select is visually
// hidden but covers the chip — taps open the platform picker. The chip
// re-renders with the chosen option's label.
// Shorter chip labels than what the sheet's `Check size (USD)` /
// `Investment horizon` produce — the chip is narrow, the parenthetical/
// long words wrap or truncate. The native select retains the full label
// as aria-label so accessibility stays correct.
const _MOBILE_CHIP_SHORT = {
  en: { residency: "Residency", checkSize: "Check size", horizon: "Horizon" },
  es: { residency: "Residencia", checkSize: "Cheque", horizon: "Horizonte" },
};

function MobileFilterChip({ filter, value, onChange, lang, dark }) {
  const fullLbl = window.pickLang(filter.label, lang) || filter.key;
  const lbl = (_MOBILE_CHIP_SHORT[lang] && _MOBILE_CHIP_SHORT[lang][filter.key]) || fullLbl;
  const opts = filter.options || [];
  const current = opts.find(o => o.value === value);
  const currentLabel = current ? window.pickLang(current.label, lang) : null;
  const placeholder = lang === "es" ? "Cualquier" : "Any";
  // Chip lights lime only once a value is selected; default state sits in a
  // neutral paper/cream surface so the lime reads as "active filter."
  const isActive = !!value;
  const bg = isActive ? "#EDFE38" : (dark ? "#1A1817" : "#FFFFFF");
  const borderColor = isActive ? "#393433" : (dark ? "#2A2825" : "#E2E0DF");
  const fg = isActive ? "#393433" : (dark ? "#FAF7F3" : "#393433");
  return (
    <label style={{
      position: "relative",
      flex: "1 1 0",
      minWidth: 0,
      display: "block",
      background: bg,
      border: `1px solid ${borderColor}`,
      padding: "10px 26px 10px 12px",
      cursor: "pointer",
      color: fg,
    }}>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 9.5,
        letterSpacing: "0.16em", textTransform: "uppercase",
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
      }}>
        {lbl}
      </div>
      <div style={{
        fontFamily: "var(--font-display)", fontSize: 15,
        letterSpacing: "-0.01em", lineHeight: 1.1, marginTop: 2,
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
      }}>
        {currentLabel || placeholder}
      </div>
      <span aria-hidden="true" style={{
        position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
        fontSize: 10, lineHeight: 1, pointerEvents: "none",
      }}>▼</span>
      <select
        value={value || ""}
        onChange={(e) => onChange(e.target.value || null)}
        aria-label={fullLbl}
        style={{
          position: "absolute", inset: 0,
          width: "100%", height: "100%",
          opacity: 0, cursor: "pointer",
          fontSize: 16, // prevents iOS zoom on focus
        }}>
        <option value="">{placeholder}</option>
        {opts.map(o => (
          <option key={o.value} value={o.value}>
            {window.pickLang(o.label, lang) || o.value}
          </option>
        ))}
      </select>
    </label>
  );
}

function MobileTopBar({ t, lang, setLang, currency, setCurrency, dark, profile, setProfile }) {
  const ink = _mfInk(dark);
  const muted = _mfMuted(dark);
  const border = _mfBorder(dark);
  const surface = _mfSurface(dark);

  const filters = window.FILTERS || [];
  const visibleKeys = ["residency", "checkSize", "horizon"];
  const visibleFilters = visibleKeys
    .map(k => filters.find(f => f.key === k))
    .filter(Boolean);

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 10,
      background: surface,
      borderBottom: `1px solid ${border}`,
      padding: "var(--safe-top, 0px) 14px 10px",
    }}>
      <div style={{
        height: 56,
        display: "flex", alignItems: "center", gap: 10,
      }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 10, minWidth: 0, flex: 1,
        }}>
          <ReurbanoMarkSmall dark={dark}/>
          <span style={{
            width: 1, height: 14, background: border, flexShrink: 0,
          }}/>
          <span style={{
            fontFamily: "var(--font-display)", fontSize: 18,
            letterSpacing: "-0.01em", color: ink, whiteSpace: "nowrap",
            overflow: "hidden", textOverflow: "ellipsis",
          }}>
            {lang === "es" ? "Oportunidades" : "Opportunities"}
          </span>
        </div>

        <MobileSegToggle
          value={lang}
          onChange={setLang}
          options={[{ value: "en", label: "EN" }, { value: "es", label: "ES" }]}
          dark={dark}
          ariaLabel={lang === "es" ? "Idioma" : "Language"}
        />
      </div>

      <div style={{
        display: "flex", gap: 8, marginTop: 4,
      }}>
        {visibleFilters.map(f => (
          <MobileFilterChip
            key={f.key}
            filter={f}
            value={profile[f.key] || ""}
            onChange={(v) => setProfile(prev => ({ ...prev, [f.key]: v }))}
            lang={lang}
            dark={dark}
          />
        ))}
      </div>

    </header>
  );
}

function ReurbanoMarkSmall({ dark }) {
  // Compact wordmark — the existing /logo.svg is meant for larger sizes.
  return (
    <img
      src={dark ? "/logo-dark.svg" : "/logo.svg"}
      alt="Reurbano"
      style={{ height: 22, width: "auto", display: "block" }}
    />
  );
}

function MobileStatsBar({ columns, lang, dark, onCollapseAll }) {
  const muted = _mfMuted(dark);
  const ink = _mfInk(dark);

  const total = columns.length;
  const fit = columns.filter(c => {
    for (const cell of c.cells.values()) {
      if (cell.eligible || cell.strategicActive) return true;
    }
    return false;
  }).length;

  const projectsLabel = lang === "es"
    ? (total === 1 ? "PROYECTO" : "PROYECTOS")
    : (total === 1 ? "PROJECT" : "PROJECTS");
  const fitLabel = lang === "es" ? "ENCAJAN" : "FIT YOUR PROFILE";

  return (
    <div style={{
      padding: "14px 16px 10px",
      display: "flex", alignItems: "center", justifyContent: "space-between",
      gap: 12,
      fontFamily: "var(--font-mono)", fontSize: 10.5,
      letterSpacing: "0.14em", textTransform: "uppercase",
      color: ink,
    }}>
      <div>
        <span>{total} {projectsLabel}</span>
      </div>
      {onCollapseAll && (
        <button
          type="button"
          onClick={onCollapseAll}
          style={{
            background: "transparent", border: "none", padding: 0,
            color: "#4866B2",
            fontFamily: "var(--font-mono)", fontSize: 10.5,
            letterSpacing: "0.14em", textTransform: "uppercase",
            cursor: "pointer",
            textDecoration: "underline", textUnderlineOffset: 3,
          }}>
          {lang === "es" ? "Colapsar todo" : "Collapse all"}
        </button>
      )}
    </div>
  );
}

function MobileFeed({ columns, profile, t, lang, dark, currency, onSelectProduct }) {
  const ranked = _useMemoMF(() => {
    const withScore = columns.map((c, i) => {
      let score = 0;
      for (const cell of c.cells.values()) {
        if (cell.eligible || cell.strategicActive) score++;
      }
      return { c, i, score };
    });
    withScore.sort((a, b) => {
      if (b.score !== a.score) return b.score - a.score;
      return a.i - b.i;
    });
    return withScore.map(x => x.c);
  }, [columns]);

  const mutedColor = dark ? "#8A827F" : "#6B6361";
  return (
    <div style={{
      padding: "0 14px 32px",
      display: "flex", flexDirection: "column", gap: 14,
    }}>
      {ranked.map((col) => (
        <window.MobileProjectCard
          key={col.name}
          column={col}
          profile={profile}
          t={t}
          lang={lang}
          dark={dark}
          currency={currency}
          onSelectProduct={onSelectProduct}
        />
      ))}
      {/* Same denomination + LP-level disclaimer the desktop header shows.
          On phones the header is too cramped for two italic lines so it
          lives at the bottom of the feed instead. */}
      {t.denominationNote && (
        <p style={{
          margin: "16px 6px 0",
          fontSize: 11, lineHeight: 1.4, color: mutedColor,
          fontStyle: "italic", textAlign: "center",
          whiteSpace: "pre-line",
        }}>
          {t.denominationNote}
        </p>
      )}
    </div>
  );
}

Object.assign(window, { MobileTopBar, MobileStatsBar, MobileFeed, MobileSegToggle, MobileFilterChip });
