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

// ═══════════════════════════════════════════════════════════════
// SHORTLIST / COMPARE
// id-based set; persisted by parent App
// ═══════════════════════════════════════════════════════════════

const SHORTLIST_MAX = 6;

window.SHORTLIST_MAX = SHORTLIST_MAX;

// Small star button rendered inside a tower floor
// NOTE: rendered as <span role="button"> because it's nested inside another <button> (the floor)
function ShortlistStar({ id, shortlist, toggle, dark, onHoverInfo }) {
  const on = shortlist.includes(id);
  const canAdd = on || shortlist.length < SHORTLIST_MAX;
  const muted = dark ? "#8A827F" : "#6B6361";
  const text = dark ? "#FAF7F3" : "#393433";
  const accent = "#4866B2";

  const handle = (e) => {
    e.stopPropagation();
    e.preventDefault();
    if (canAdd) toggle(id);
  };

  return (
    <span
      role="button"
      tabIndex={canAdd ? 0 : -1}
      aria-label={on ? "Remove from shortlist" : "Add to shortlist"}
      aria-pressed={on}
      aria-disabled={!canAdd}
      onClick={handle}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") handle(e);
      }}
      onMouseEnter={() => onHoverInfo && onHoverInfo(canAdd ? null : "Shortlist full")}
      onMouseLeave={() => onHoverInfo && onHoverInfo(null)}
      style={{
        width: 20, height: 20, padding: 0,
        cursor: canAdd ? "pointer" : "not-allowed",
        opacity: canAdd ? 1 : 0.35,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0,
      }}>
      <svg width="13" height="13" viewBox="0 0 13 13" aria-hidden="true">
        <path d="M6.5 1 L8 4.6 L12 5 L9 7.8 L9.8 12 L6.5 9.8 L3.2 12 L4 7.8 L1 5 L5 4.6 Z"
          fill={on ? accent : "transparent"}
          stroke={on ? accent : (dark ? muted : text)}
          strokeWidth="1.1"
          strokeLinejoin="round"/>
      </svg>
    </span>
  );
}
window.ShortlistStar = ShortlistStar;

// Floating pill showing shortlist count + opens drawer
function ShortlistPill({ count, onClick, dark, t }) {
  if (count === 0) return null;
  const text = dark ? "#FAF7F3" : "#393433";
  const surface = dark ? "#1A1817" : "#FFFFFF";
  const border = dark ? "#2A2825" : "#393433";
  const accent = "#4866B2";

  return (
    <button type="button" onClick={onClick} className="r-shortlist-pill" style={{
      position: "fixed", bottom: 20, left: "50%", transform: "translateX(-50%)",
      zIndex: 60,
      padding: "10px 18px",
      background: surface, color: text,
      border: `1px solid ${border}`,
      display: "inline-flex", alignItems: "center", gap: 10,
      fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
      cursor: "pointer",
      boxShadow: "0 10px 28px rgba(0,0,0,0.18)",
      animation: "slpill 260ms cubic-bezier(.22,.61,.36,1) both",
    }}>
      <svg width="13" height="13" viewBox="0 0 13 13" aria-hidden="true">
        <path d="M6.5 1 L8 4.6 L12 5 L9 7.8 L9.8 12 L6.5 9.8 L3.2 12 L4 7.8 L1 5 L5 4.6 Z" fill={accent} stroke={accent} strokeWidth="1.1" strokeLinejoin="round"/>
      </svg>
      <span>{t.compareCta}</span>
      <span style={{ padding: "2px 7px", background: accent, color: "#FFFFFF", fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>{count}</span>
    </button>
  );
}
window.ShortlistPill = ShortlistPill;

// Full compare drawer — slides up from bottom
function CompareDrawer({ visible, onClose, shortlist, setShortlist, t, lang, dark }) {
  useEffect(() => {
    if (!visible) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [visible, onClose]);

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

  const items = useMemo(() => {
    const byId = new Map((window.PRODUCTS || []).map(p => [p.id, p]));
    return shortlist.map(id => byId.get(id)).filter(Boolean);
  }, [shortlist]);

  if (!visible) return null;

  const remove = (id) => setShortlist(shortlist.filter(x => x !== id));
  const clear = () => setShortlist([]);

  return (
    <Fragment>
      <div onClick={onClose} style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)",
        zIndex: 70, animation: "fadeIn 200ms ease both",
      }}/>
      <div role="dialog" aria-label="Compare shortlisted investments" className="r-compare" style={{
        position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 71,
        background: surface, color: text,
        borderTop: `1px solid ${border}`,
        maxHeight: "78vh", overflow: "auto",
        animation: "slideUp 320ms cubic-bezier(.22,.61,.36,1) both",
        boxShadow: "0 -12px 32px rgba(0,0,0,0.22)",
      }}>
        {/* Drawer header */}
        <div style={{
          padding: "18px 28px 14px",
          borderBottom: `1px solid ${border}`,
          display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24,
          position: "sticky", top: 0, background: surface, zIndex: 2,
        }}>
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: muted, marginBottom: 6 }}>
              {lang === "en" ? "Reurbano · Shortlist" : "Reurbano · Shortlist"}
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 24, letterSpacing: "-0.02em", color: text, lineHeight: 1 }}>
              {t.compareTitle}
            </div>
            <div style={{ fontSize: 12, color: muted, marginTop: 6, maxWidth: 520 }}>
              {t.compareSub}
            </div>
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <button onClick={clear} style={{
              padding: "8px 12px",
              background: "transparent", color: text, border: `1px solid ${border}`,
              fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase",
              cursor: "pointer",
            }}>{t.clearAll}</button>
            <button onClick={onClose} aria-label="Close" style={{
              width: 34, height: 34, background: "transparent", border: `1px solid ${border}`, color: text,
              cursor: "pointer", fontSize: 16, lineHeight: 1,
            }}>×</button>
          </div>
        </div>

        {/* Compare grid */}
        <div style={{ padding: "20px 28px" }}>
          {items.length === 0 ? (
            <div style={{ padding: "48px 0", textAlign: "center", color: muted, fontSize: 13 }}>
              {t.compareEmpty}
            </div>
          ) : (
            <div style={{
              display: "grid",
              gridTemplateColumns: `180px repeat(${items.length}, minmax(200px, 1fr))`,
              gap: 0, alignItems: "stretch",
              border: `1px solid ${border}`,
              fontSize: 12.5,
            }}>
              {/* Row: Project */}
              <RowLabel label={t.project} dark={dark}/>
              {items.map(p => (
                <CellTop key={`h-${p.id}`} p={p} t={t} lang={lang} dark={dark} onRemove={() => remove(p.id)}/>
              ))}

              {/* Row: Tier */}
              <RowLabel label={t.tier} dark={dark}/>
              {items.map(p => {
                const tier = window.productTier(p);
                const tierMeta = window.TIER_LABELS?.[tier];
                return (
                  <Cell key={`t-${p.id}`} dark={dark}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em", color: muted, textTransform: "uppercase" }}>
                      {tierMeta?.short || tier}
                    </div>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 14, letterSpacing: "-0.01em", color: text, marginTop: 4, lineHeight: 1.15 }}>
                      {tierMeta?.[lang] || p.type}
                    </div>
                  </Cell>
                );
              })}

              {/* Row: Return */}
              <RowLabel label={t.returnRange} dark={dark}/>
              {items.map(p => (
                <Cell key={`r-${p.id}`} dark={dark}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 20, letterSpacing: "-0.01em", color: text, fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>
                    {window.formatRangeStr(p)}
                  </div>
                </Cell>
              ))}

              {/* Row: Hold */}
              <RowLabel label={t.holdPeriod} dark={dark}/>
              {items.map(p => (
                <Cell key={`h2-${p.id}`} dark={dark}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: text, fontVariantNumeric: "tabular-nums" }}>
                    {p.holdPeriodYears[0]}–{p.holdPeriodYears[1]} {t.yrs}
                  </div>
                </Cell>
              ))}

              {/* Row: Min */}
              <RowLabel label={t.minInvestment} dark={dark}/>
              {items.map(p => (
                <Cell key={`m-${p.id}`} dark={dark}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: text, fontVariantNumeric: "tabular-nums" }}>
                    {window.formatCurrency(p.minimumInvestment.amount)}
                  </div>
                  {p.accreditedOnly && (
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: muted, marginTop: 4 }}>
                      {t.accreditedOnly}
                    </div>
                  )}
                </Cell>
              ))}

              {/* Row: Status */}
              <RowLabel label={t.status || (lang === "en" ? "Status" : "Estado")} dark={dark}/>
              {items.map(p => (
                <Cell key={`s-${p.id}`} dark={dark}>
                  <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 6, height: 6, borderRadius: "50%", background: window.STATUS_DOT[p.status] }}/>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: text }}>
                      {window.STATUS_LABEL[p.status][lang]}
                    </span>
                  </div>
                </Cell>
              ))}

              {/* Row: Risks */}
              <RowLabel label={t.riskFactors} dark={dark}/>
              {items.map(p => (
                <Cell key={`rk-${p.id}`} dark={dark}>
                  <ul style={{ margin: 0, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 4 }}>
                    {(p.riskFactors || []).slice(0, 2).map((r, i) => (
                      <li key={i} style={{ fontSize: 11.5, color: muted, lineHeight: 1.35, position: "relative", paddingLeft: 10 }}>
                        <span style={{ position: "absolute", left: 0, top: 7, width: 4, height: 1, background: faint }}/>
                        {r}
                      </li>
                    ))}
                  </ul>
                </Cell>
              ))}
            </div>
          )}

          {items.length > 0 && (
            <div style={{
              marginTop: 20, padding: "16px 0 4px",
              borderTop: `1px dashed ${border}`,
              display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap",
            }}>
              <div style={{ fontSize: 12, color: muted, maxWidth: 560, lineHeight: 1.5 }}>
                {t.compareFooter}
              </div>
              <button onClick={() => alert(t.compareMailSent)} style={{
                padding: "10px 18px",
                background: accent, color: "#FFFFFF", border: "none",
                fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
                cursor: "pointer",
              }}>{t.emailShortlist}</button>
            </div>
          )}
        </div>
      </div>
    </Fragment>
  );
}

function RowLabel({ label, dark }) {
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const surface = dark ? "#1A1817" : "#F6F2EC";
  return (
    <div style={{
      padding: "12px 14px",
      background: surface,
      borderBottom: `1px solid ${border}`,
      borderRight: `1px solid ${border}`,
      fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted,
      display: "flex", alignItems: "center",
    }}>
      {label}
    </div>
  );
}

function Cell({ children, dark }) {
  const border = dark ? "#2A2825" : "#E2E0DF";
  return (
    <div style={{
      padding: "12px 14px",
      borderBottom: `1px solid ${border}`,
      borderRight: `1px solid ${border}`,
    }}>
      {children}
    </div>
  );
}

function CellTop({ p, t, lang, dark, onRemove }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  return (
    <div style={{
      padding: "12px 14px",
      borderBottom: `1px solid ${border}`,
      borderRight: `1px solid ${border}`,
      display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8,
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 14, letterSpacing: "-0.01em", color: text, lineHeight: 1.15 }}>
          {p.project}
        </div>
        <div style={{ fontSize: 11, color: muted, marginTop: 3 }}>
          {p.projectCity}
        </div>
      </div>
      <button onClick={onRemove} aria-label="Remove" style={{
        width: 22, height: 22, padding: 0,
        background: "transparent", border: "none", color: muted, cursor: "pointer",
        fontSize: 14, lineHeight: 1, flexShrink: 0,
      }}>×</button>
    </div>
  );
}

window.CompareDrawer = CompareDrawer;
