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

// ═══════════════════════════════════════════════════════════════
// TWEAKS PANEL
// ═══════════════════════════════════════════════════════════════
function TweaksPanel({ tweaks, setTweaks, t, visible, onClose }) {
  const dark = tweaks.dark;
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const bg = dark ? "#1A1817" : "#FFFFFF";
  const accent = "#4866B2";

  if (!visible) return null;

  const persist = (partial) => {
    setTweaks({ ...tweaks, ...partial });
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: partial }, "*");
  };

  return (
    <div className="r-tweaks" style={{
      position: "fixed", bottom: 16, right: 16, width: 288, zIndex: 80,
      background: bg, border: `1px solid ${border}`, color: text,
      fontFamily: "var(--font-body)",
      boxShadow: "0 12px 32px rgba(0,0,0,0.18)",
    }}>
      <div style={{ padding: "12px 16px", borderBottom: `1px solid ${border}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 14, letterSpacing: "-0.01em" }}>Tweaks</div>
        <button onClick={onClose} style={{ background: "transparent", border: "none", color: muted, cursor: "pointer", fontSize: 14, lineHeight: 1 }}>×</button>
      </div>
      <div style={{ padding: "12px 16px", display: "flex", flexDirection: "column", gap: 14 }}>
        <SegmentRow label={t.language} value={tweaks.lang} options={[["EN","en"],["ES","es"]]} onChange={v => persist({ lang: v })} dark={dark}/>
        <SegmentRow label={t.teaching} value={tweaks.teaching} options={[[t.basic,"basic"],[t.intermediate,"intermediate"],[t.pro,"pro"]]} onChange={v => persist({ teaching: v })} dark={dark}/>
        <SegmentRow label={t.density} value={tweaks.density} options={[[t.compact,"compact"],[t.comfortable,"comfortable"]]} onChange={v => persist({ density: v })} dark={dark}/>
        <SegmentRow label={t.theme} value={tweaks.dark ? "dark" : "light"} options={[[t.light,"light"],[t.dark,"dark"]]} onChange={v => persist({ dark: v === "dark" })} dark={dark}/>
        <SegmentRow label={t.highlight} value={tweaks.highlight} options={[[t.none,"none"],[t.byTier,"byTier"],[t.byReturn,"byReturn"]]} onChange={v => persist({ highlight: v })} dark={dark}/>
        <ToggleRow label={t.hideIneligible} value={tweaks.hideIneligible} onChange={v => persist({ hideIneligible: v })} dark={dark}/>
      </div>
    </div>
  );
}

function SegmentRow({ label, value, options, onChange, dark }) {
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const text = dark ? "#FAF7F3" : "#393433";
  const accent = "#4866B2";
  return (
    <div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: muted, marginBottom: 5 }}>{label}</div>
      <div style={{ display: "flex", border: `1px solid ${border}` }}>
        {options.map(([lbl, v]) => (
          <button key={v} onClick={() => onChange(v)} style={{
            flex: 1, padding: "6px 4px", fontSize: 11, cursor: "pointer",
            background: v === value ? accent : "transparent",
            color: v === value ? "#fff" : text,
            border: "none", borderRight: `1px solid ${border}`,
            fontFamily: "var(--font-body)",
          }}>{lbl}</button>
        ))}
      </div>
    </div>
  );
}

function ToggleRow({ label, value, onChange, dark }) {
  const muted = dark ? "#8A827F" : "#6B6361";
  const accent = "#4866B2";
  const border = dark ? "#2A2825" : "#E2E0DF";
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: muted }}>{label}</div>
      <button onClick={() => onChange(!value)} style={{
        width: 36, height: 18, padding: 2, border: `1px solid ${border}`, background: value ? accent : "transparent",
        cursor: "pointer", position: "relative",
      }}>
        <span style={{ display: "block", width: 12, height: 12, background: value ? "#fff" : (dark ? "#FAF7F3" : "#393433"),
          transform: value ? "translateX(16px)" : "translateX(0)", transition: "transform 160ms" }}/>
      </button>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// MAIN APP
// ═══════════════════════════════════════════════════════════════
function App() {
  const DEFAULTS = /*EDITMODE-BEGIN*/{
    "lang": "en",
    "teaching": "basic",
    "density": "comfortable",
    "dark": false,
    "highlight": "none",
    "hideIneligible": false
  }/*EDITMODE-END*/;
  const [tweaks, setTweaks] = useState(DEFAULTS);
  const [tweaksVisible, setTweaksVisible] = useState(false);

  // Edit-mode protocol
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data;
      if (!d || typeof d !== "object") return;
      if (d.type === "__activate_edit_mode") setTweaksVisible(true);
      if (d.type === "__deactivate_edit_mode") setTweaksVisible(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  window.__teaching = tweaks.teaching;

  // Shared persist helper (updates tweaks state + writes to file via edit-mode)
  const persistTweak = (partial) => {
    setTweaks({ ...tweaks, ...partial });
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: partial }, "*");
  };

  const [profile, setProfile] = useState(() => {
    try { return JSON.parse(localStorage.getItem("reurbano-profile-v2")) || {}; }
    catch { return {}; }
  });
  useEffect(() => {
    try { localStorage.setItem("reurbano-profile-v2", JSON.stringify(profile)); } catch {}
  }, [profile]);
  const onReset = () => setProfile({});

  const [selected, setSelected] = useState(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [sortMode, setSortMode] = useState("match"); // "match" | "status" | "stack"
  const [statusFilter, setStatusFilter] = useState("all"); // "all" | "open" | "coming-soon" | "closed"
  const [shortlist, setShortlist] = useState(() => {
    try { return JSON.parse(localStorage.getItem("reurbano-shortlist-v1")) || []; }
    catch { return []; }
  });
  const [compareOpen, setCompareOpen] = useState(false);
  useEffect(() => {
    try { localStorage.setItem("reurbano-shortlist-v1", JSON.stringify(shortlist)); } catch {}
  }, [shortlist]);
  const toggleShortlist = (id) => {
    setShortlist(s => {
      if (s.includes(id)) return s.filter(x => x !== id);
      if (s.length >= (window.SHORTLIST_MAX || 6)) return s;
      return [...s, id];
    });
  };

  const t = STRINGS[tweaks.lang];
  const allColumns = useMemo(() => window.buildColumns(PRODUCTS, profile), [profile]);

  // Count projects by status — drives the ribbon
  const statusCounts = useMemo(() => {
    const counts = { open: 0, "coming-soon": 0, closed: 0 };
    for (const col of allColumns) {
      const s = col.products[0]?.status || "open";
      if (counts[s] != null) counts[s]++;
    }
    return counts;
  }, [allColumns]);

  // Apply status filter, then sort
  const columns = useMemo(() => {
    let cols = statusFilter === "all"
      ? allColumns.slice()
      : allColumns.filter(c => (c.products[0]?.status || "open") === statusFilter);

    if (sortMode === "match") {
      cols.sort((a, b) => {
        const ae = Array.from(a.cells.values()).filter(c => c.eligible).length;
        const be = Array.from(b.cells.values()).filter(c => c.eligible).length;
        if (be !== ae) return be - ae;
        // tiebreaker: more cells overall, then alphabetical
        if (b.cells.size !== a.cells.size) return b.cells.size - a.cells.size;
        return a.name.localeCompare(b.name);
      });
    } else if (sortMode === "status") {
      const rank = { "open": 0, "coming-soon": 1, "closed": 2 };
      cols.sort((a, b) => {
        const ra = rank[a.products[0]?.status || "open"] ?? 9;
        const rb = rank[b.products[0]?.status || "open"] ?? 9;
        if (ra !== rb) return ra - rb;
        return a.name.localeCompare(b.name);
      });
    } else if (sortMode === "stack") {
      cols.sort((a, b) => b.cells.size - a.cells.size);
    }
    return cols;
  }, [allColumns, sortMode, statusFilter]);

  const bg = tweaks.dark ? "#0D0D0D" : "#FAF7F3";
  const text = tweaks.dark ? "#FAF7F3" : "#393433";

  // Close sidebar on ESC
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setSidebarOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <div className={tweaks.dark ? "dark" : ""} style={{
      display: "flex", height: "100vh", width: "100%",
      background: bg, color: text,
      fontFamily: "var(--font-body)", fontWeight: 400,
      overflow: "hidden",
    }}>
      <div className={`r-backdrop${sidebarOpen ? " is-open" : ""}`} onClick={() => setSidebarOpen(false)}/>
      <div className={`r-sidebar${sidebarOpen ? " is-open" : ""}`} style={{ display: "flex", flexShrink: 0 }}>
        <window.Sidebar
          profile={profile} setProfile={setProfile} t={t} lang={tweaks.lang} dark={tweaks.dark}
          onReset={onReset}
          onClose={() => setSidebarOpen(false)}
          products={PRODUCTS}
        />
      </div>
      <main style={{ flex: 1, overflow: "auto", position: "relative", minWidth: 0 }}>
        <window.MatrixHeader columns={columns} allColumnsCount={allColumns.length} profile={profile} products={PRODUCTS} t={t} lang={tweaks.lang} dark={tweaks.dark} setLang={(v) => persistTweak({ lang: v })} onOpenSidebar={() => setSidebarOpen(true)}/>
        <window.StatusRibbon counts={statusCounts} total={allColumns.length} active={statusFilter} setActive={setStatusFilter} t={t} dark={tweaks.dark} sortMode={sortMode} setSortMode={setSortMode}/>
        <window.MatrixC
          columns={columns} profile={profile} t={t} lang={tweaks.lang} dark={tweaks.dark}
          selectedId={selected?.id} onSelectProduct={setSelected}
          density={tweaks.density} highlight={tweaks.highlight} hideIneligible={tweaks.hideIneligible}
          onSetHideIneligible={(v) => persistTweak({ hideIneligible: v })}
          statusFilter={statusFilter} onClearStatus={() => setStatusFilter("all")}
          shortlist={shortlist} toggleShortlist={toggleShortlist}
        />
      </main>
      <window.DetailPanel product={selected} onClose={() => setSelected(null)} t={t} lang={tweaks.lang} dark={tweaks.dark} shortlist={shortlist} toggleShortlist={toggleShortlist} profile={profile} allProducts={PRODUCTS} onSelectProduct={setSelected}/>
      <window.ShortlistPill count={shortlist.length} onClick={() => setCompareOpen(true)} dark={tweaks.dark} t={t}/>
      <window.CompareDrawer visible={compareOpen} onClose={() => setCompareOpen(false)} shortlist={shortlist} setShortlist={setShortlist} t={t} lang={tweaks.lang} dark={tweaks.dark}/>
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} t={t} visible={tweaksVisible} onClose={() => setTweaksVisible(false)}/>
    </div>
  );
}

function NarrativeStrip({ t, lang, dark }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const surface = dark ? "#0D0D0D" : "#FAF7F3";
  const accent = "#4866B2";
  const lime = "#EDFE38";

  const STORAGE = "r-narr-collapsed-v1";
  const [collapsed, setCollapsed] = React.useState(() => {
    try { return localStorage.getItem(STORAGE) === "1"; } catch { return false; }
  });
  const toggle = () => {
    setCollapsed(v => {
      try { localStorage.setItem(STORAGE, !v ? "1" : "0"); } catch {}
      return !v;
    });
  };

  const beats = [
    { n: "01", title: t.narr1Title, body: t.narr1Body, icon: (
      <svg width="26" height="26" viewBox="0 0 26 26" fill="none" aria-hidden="true">
        <rect x="5" y="17" width="16" height="5" fill={accent}/>
        <rect x="5" y="11" width="16" height="5" fill={dark ? "#6D85C3" : "#A1B0D4"}/>
        <rect x="5" y="6"  width="16" height="4" fill={lime} stroke={dark ? "#7A7818" : "#9C9A18"} strokeWidth="0.5"/>
      </svg>
    )},
    { n: "02", title: t.narr2Title, body: t.narr2Body, icon: (
      <svg width="26" height="26" viewBox="0 0 26 26" fill="none" aria-hidden="true">
        <rect x="4.5" y="6" width="17" height="15" stroke={muted} strokeWidth="1.1" fill="none"/>
        <rect x="4.5" y="6"  width="17" height="4" fill={dark ? "#2D3A1F" : "#FAFFCE"}/>
        <rect x="4.5" y="10" width="17" height="4" fill="transparent"/>
        <rect x="4.5" y="14" width="17" height="3" fill={dark ? "#2D3A1F" : "#FAFFCE"}/>
        <rect x="4.5" y="17" width="17" height="4" fill="transparent"/>
        <line x1="4.5" y1="10" x2="21.5" y2="10" stroke={muted} strokeWidth="0.7"/>
        <line x1="4.5" y1="14" x2="21.5" y2="14" stroke={muted} strokeWidth="0.7"/>
        <line x1="4.5" y1="17" x2="21.5" y2="17" stroke={muted} strokeWidth="0.7"/>
      </svg>
    )},
    { n: "03", title: t.narr3Title, body: t.narr3Body, icon: (
      <svg width="26" height="26" viewBox="0 0 26 26" fill="none" aria-hidden="true">
        <rect x="4" y="7" width="7" height="14" fill="none" stroke={muted} strokeWidth="1"/>
        <rect x="14.5" y="7" width="7" height="14" fill="none" stroke={muted} strokeWidth="1"/>
        <rect x="14.5" y="12" width="7" height="4" fill={lime}/>
        <rect x="4" y="16" width="7" height="3" fill={lime}/>
        <path d="M4 11h7M4 14h7M4 19h7" stroke={muted} strokeWidth="0.6" strokeDasharray="1.5 1.5"/>
        <path d="M14.5 10h7M14.5 18h7" stroke={muted} strokeWidth="0.6" strokeDasharray="1.5 1.5"/>
      </svg>
    )},
  ];

  return (
    <div className="r-narr-strip" style={{
      borderBottom: `1px solid ${border}`,
      background: surface,
      padding: collapsed ? "6px 28px" : "14px 28px 16px",
      transition: "padding 200ms",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em",
          textTransform: "uppercase", color: muted,
        }}>
          {t.narrHow}
        </div>
        <button onClick={toggle} aria-label={collapsed ? "Expand" : "Collapse"} style={{
          background: "transparent", border: "none", cursor: "pointer",
          fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em",
          textTransform: "uppercase", color: muted,
          padding: "4px 6px", display: "inline-flex", alignItems: "center", gap: 6,
        }}>
          <span>{collapsed ? (lang === "en" ? "Show" : "Mostrar") : (lang === "en" ? "Hide" : "Ocultar")}</span>
          <svg width="10" height="6" viewBox="0 0 10 6" fill="none" aria-hidden="true" style={{ transform: collapsed ? "rotate(0deg)" : "rotate(180deg)", transition: "transform 200ms" }}>
            <path d="M1 1l4 4 4-4" stroke="currentColor" strokeWidth="1.3" fill="none"/>
          </svg>
        </button>
      </div>
      {!collapsed && (
        <div className="r-narr-beats" style={{
          display: "grid",
          gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
          gap: 20,
          marginTop: 10,
          alignItems: "start",
        }}>
          {beats.map((b, i) => (
            <div key={b.n} style={{
              display: "flex", alignItems: "flex-start", gap: 12,
              position: "relative",
              paddingLeft: i === 0 ? 0 : 18,
            }}>
              {i > 0 && (
                <div aria-hidden="true" style={{
                  position: "absolute", left: 0, top: 8, width: 8, color: muted,
                }}>
                  <svg width="8" height="10" viewBox="0 0 8 10" fill="none"><path d="M1 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" fill="none"/></svg>
                </div>
              )}
              <div style={{ flexShrink: 0, marginTop: 0 }}>{b.icon}</div>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.1em", color: muted, fontVariantNumeric: "tabular-nums" }}>
                    {b.n}
                  </span>
                  <span style={{ fontFamily: "var(--font-display)", fontSize: 13.5, color: text, letterSpacing: "-0.01em", lineHeight: 1.15 }}>
                    {b.title}
                  </span>
                </div>
                <div style={{ fontSize: 11.5, color: muted, marginTop: 4, lineHeight: 1.45, letterSpacing: "-0.003em" }}>
                  {b.body}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// ERROR BOUNDARY
// ═══════════════════════════════════════════════════════════════
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { console.error("[Reurbano] render failed:", error, info); }
  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div style={{
        minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
        background: "#FAF7F3", color: "#393433", padding: 24,
        fontFamily: "'Tomato Grotesk', system-ui, sans-serif",
      }}>
        <div style={{ maxWidth: 480, border: "1px solid #E2E0DF", padding: "28px 32px", background: "#FFFFFF" }}>
          <div style={{ fontFamily: "'Neue Machina', system-ui, sans-serif", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "#6B6361", marginBottom: 10 }}>
            Reurbano · Investor
          </div>
          <div style={{ fontFamily: "'Neue Machina', system-ui, sans-serif", fontSize: 26, letterSpacing: "-0.02em", lineHeight: 1.1, marginBottom: 10 }}>
            Something broke loading this view.
          </div>
          <div style={{ fontSize: 13.5, color: "#6B6361", lineHeight: 1.55, marginBottom: 18 }}>
            We couldn't render the investment matrix. Your saved profile is safe. Reload to try again, or reset if the problem persists.
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={() => location.reload()} style={{
              padding: "9px 16px", border: "none", background: "#4866B2", color: "#FFFFFF",
              fontFamily: "inherit", fontSize: 12.5, letterSpacing: "0.02em", cursor: "pointer",
            }}>Reload</button>
            <button onClick={() => { try { localStorage.clear(); } catch {}; location.reload(); }} style={{
              padding: "9px 16px", border: "1px solid #E2E0DF", background: "transparent", color: "#393433",
              fontFamily: "inherit", fontSize: 12.5, letterSpacing: "0.02em", cursor: "pointer",
            }}>Reset & reload</button>
          </div>
          {this.state.error && (
            <details style={{ marginTop: 18, fontSize: 11, color: "#8A827F", fontFamily: "ui-monospace, monospace" }}>
              <summary style={{ cursor: "pointer" }}>Technical details</summary>
              <pre style={{ whiteSpace: "pre-wrap", marginTop: 8 }}>{String(this.state.error)}</pre>
            </details>
          )}
        </div>
      </div>
    );
  }
}

ReactDOM.createRoot(document.getElementById("root")).render(<ErrorBoundary><App/></ErrorBoundary>);
