/* Screen — Srovnávač (compares issuers side-by-side, max 4) */
function CompareScreen({ go, compare }) {
  const items = compare.items();
  const [adding, setAdding] = React.useState(false);
  const canAdd = items.length < 4;

  const rows = [
    { label: "Schválených emisí", hi: true, render: (b) => <span className="num" style={{ fontWeight: 600, color: "var(--accent-strong)" }}>{b.bondCount}</span> },
    { label: "Kraj", render: (b) => b.region || "–" },
    { label: "Sídlo", render: (b) => b.city || "–" },
    { label: "První schválení", render: (b) => <span className="num">{b.earliestApprovalStr || "–"}</span> },
    { label: "Poslední schválení", render: (b) => <span className="num">{b.latestApprovalStr || "–"}</span> },
    { label: "Typ dokumentace", render: (b) => b.docTypes || "–" },
    { label: "Typ subjektu", render: (b) => b.isSPV ? "SPV" : "Provozní" },
    { label: "Založeno", render: (b) => <span className="num">{b.founded || "–"}</span> },
    { label: "Základní kapitál", render: (b) => <span className="num" style={{ fontWeight: 500, color: "var(--ink)" }}>{window.fmtCZKshort(b.registeredCapital)}</span> },
    { label: "Statutární orgán", render: (b) => b.ceo ? b.ceo + (b.ceoRole ? " (" + b.ceoRole + ")" : "") : "–" },
    { label: "Spolehlivý plátce DPH", render: (b) => b.reliable ? "Ano" : "–" },
    { label: "Zveřejněné závěrky", render: (b) => <span className="num">{window.fmtInt(b.publishedAccounts)}</span> },
    { label: "Obchodní rejstřík", render: (b) => b.registryUrl ? <a href={b.registryUrl} target="_blank" rel="noopener noreferrer" style={{ color: "var(--accent-strong)", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 5, fontSize: 13.5 }}>Otevřít <Icon name="external" size={13} /></a> : <span style={{ color: "var(--faint)" }}>–</span> },
  ];

  const colCount = items.length + (canAdd ? 1 : 0);
  const template = `190px repeat(${colCount}, minmax(180px, 1fr))`;

  if (items.length === 0) {
    return (
      <div className="screen" data-screen-label="Srovnávač">
        <div className="container container-wide" style={{ padding: "32px 24px 64px" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Maximálně 4 emitenti</div>
          <h1 style={{ fontSize: 32, marginBottom: 28 }}>Srovnávač</h1>
          <div className="card empty-state" style={{ padding: "72px 32px" }}>
            <div style={{ width: 88, height: 88, margin: "0 auto", borderRadius: 16, background: "var(--surface-2)", border: "1px solid var(--line)", display: "grid", placeItems: "center", color: "var(--faint)" }}><Icon name="compare" size={38} stroke={1.3} /></div>
            <h2 style={{ fontSize: 22, marginTop: 24 }}>Zatím jste nepřidali žádné emitenty</h2>
            <p style={{ color: "var(--muted)", marginTop: 10, maxWidth: 440, marginInline: "auto", lineHeight: 1.55 }}>
              Přejděte na seznam emitentů a klikněte na <b style={{ color: "var(--ink-2)" }}>+ Srovnat</b> u těch, které chcete postavit vedle sebe a porovnat řádek po řádku.
            </p>
            <div style={{ marginTop: 24 }}><Btn variant="primary" iconRight="arrowRight" onClick={() => go("bonds")}>Procházet emitenty</Btn></div>
          </div>
          <div style={{ marginTop: 28, maxWidth: 720 }}><Disclaimer /></div>
        </div>
      </div>
    );
  }

  return (
    <div className="screen" data-screen-label="Srovnávač">
      <div className="container container-wide" style={{ padding: "32px 24px 64px" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>{items.length} ze 4 emitentů</div>
            <h1 style={{ fontSize: 32 }}>Srovnávač</h1>
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <Btn variant="ghost" size="sm" onClick={() => compare.clear()}>Vymazat vše</Btn>
            <Btn variant="primary" size="sm" icon="download" onClick={() => openLead("pdf-compare")}>Stáhnout srovnání (PDF)</Btn>
          </div>
        </div>

        <div style={{ overflowX: "auto" }}>
          <div className="compare-grid" style={{ gridTemplateColumns: template, minWidth: 190 + colCount * 190 }}>
            {/* header */}
            <div className="cglabel compare-head" style={{ background: "var(--surface)" }}></div>
            {items.map((b) => {
              return (
                <div key={b.id} className="cgcell compare-head" style={{ background: "var(--surface)", flexDirection: "column", alignItems: "flex-start", gap: 6, paddingTop: 16, paddingBottom: 16 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", width: "100%", gap: 8 }}>
                    <span className="badge badge-sector">{b.region || "ČR"}</span>
                    <button onClick={() => compare.toggle(b.id)} className="filter-tag" style={{ padding: 4, border: "1px solid var(--line)" }} aria-label="Odebrat"><Icon name="x" size={13} /></button>
                  </div>
                  <div className="bond-name" onClick={() => go("detail", { id: b.id })} style={{ fontSize: 14.5 }}>{b.shortName}</div>
                  <div className="bond-sub">{b.ico ? "IČO " + b.ico : "IČO neuvedeno"}</div>
                </div>
              );
            })}
            {canAdd && <div className="cgcell compare-head" style={{ background: "var(--surface)" }}><AddBondColumn compare={compare} adding={adding} setAdding={setAdding} /></div>}

            {/* rows */}
            {rows.map((r) => (
              <React.Fragment key={r.label}>
                <div className="cglabel">{r.label}</div>
                {items.map((b) => (
                  <div key={b.id + r.label} className="cgcell" style={{ color: "var(--ink-2)", fontSize: 14, background: r.hi ? "var(--accent-softer)" : undefined }}>{r.render(b)}</div>
                ))}
                {canAdd && <div className="cgcell" style={{ background: "var(--surface-2)" }}></div>}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 28, maxWidth: 720 }}><Disclaimer /></div>
      </div>
    </div>
  );
}

function AddBondColumn({ compare, adding, setAdding }) {
  const [q, setQ] = React.useState("");
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!adding) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) { setAdding(false); setQ(""); } };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [adding]);

  if (!adding) {
    return (
      <button onClick={() => setAdding(true)} style={{ width: "100%", border: "1.5px dashed var(--line)", background: "transparent", borderRadius: "var(--r-sm)", padding: "18px 12px", color: "var(--accent-strong)", display: "flex", flexDirection: "column", alignItems: "center", gap: 8, fontWeight: 500, fontSize: 14 }}
        onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.background = "var(--accent-softer)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.background = "transparent"; }}>
        <Icon name="plus" size={20} /> Přidat emitenta
      </button>
    );
  }
  const results = window.BONDS.filter((b) => !compare.has(b.id))
    .filter((b) => !q || b.name.toLowerCase().includes(q.toLowerCase()) || (b.ico || "").includes(q.toLowerCase()) || (b.city || "").toLowerCase().includes(q.toLowerCase()))
    .slice(0, 8);
  return (
    <div ref={ref} style={{ position: "relative", width: "100%" }}>
      <input className="input" autoFocus placeholder="Hledat emitenta…" value={q} onChange={(e) => setQ(e.target.value)} />
      <div style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", boxShadow: "var(--sh-3)", zIndex: 30, overflow: "hidden", maxHeight: 300, overflowY: "auto" }}>
        {results.length === 0 && <div style={{ padding: "14px", fontSize: 13, color: "var(--muted)" }}>Nic nenalezeno.</div>}
        {results.map((b) => (
          <button key={b.id} onClick={() => { compare.toggle(b.id); setAdding(false); setQ(""); }} style={{ display: "block", width: "100%", textAlign: "left", padding: "10px 14px", border: 0, background: "transparent", borderBottom: "1px solid var(--line-2)" }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--accent-softer)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
            <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--ink)" }}>{b.shortName}</div>
            <div className="num" style={{ fontSize: 11.5, color: "var(--faint)", marginTop: 2 }}>{b.bondCount} emisí{b.region ? " · " + b.region : ""}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CompareScreen });
