/* Screen — Seznam emitentů */
const ISSUERS_PER_PAGE = 20;

function IssuersScreen({ go }) {
  const [filters, setFilters] = React.useState({ search: "", region: "", spv: "vse" });
  const [sort, setSort] = React.useState({ key: "bondCount", dir: "desc" });
  const [page, setPage] = React.useState(1);
  const setF = (patch) => { setFilters((f) => ({ ...f, ...patch })); setPage(1); };

  const filtered = React.useMemo(() => window.ISSUERS.filter((it) => {
    if (filters.region && it.region !== filters.region) return false;
    if (filters.spv === "ano" && !it.isSPV) return false;
    if (filters.spv === "ne" && it.isSPV) return false;
    if (filters.search) {
      const q = filters.search.toLowerCase();
      const inName = it.name.toLowerCase().includes(q);
      const inCity = (it.city || "").toLowerCase().includes(q);
      const inIco = (it.ico || "").includes(q);
      if (!inName && !inCity && !inIco) return false;
    }
    return true;
  }), [filters]);

  const sorted = React.useMemo(() => {
    const arr = [...filtered]; const { key, dir } = sort;
    arr.sort((a, b) => {
      let av = a[key], bv = b[key];
      if (typeof av === "string") { av = av.toLowerCase(); bv = bv.toLowerCase(); }
      if (typeof av === "boolean") { av = av ? 1 : 0; bv = bv ? 1 : 0; }
      if (av < bv) return dir === "asc" ? -1 : 1;
      if (av > bv) return dir === "asc" ? 1 : -1;
      return 0;
    });
    return arr;
  }, [filtered, sort]);

  const pageCount = Math.max(1, Math.ceil(sorted.length / ISSUERS_PER_PAGE));
  const curPage = Math.min(page, pageCount);
  const rows = sorted.slice((curPage - 1) * ISSUERS_PER_PAGE, curPage * ISSUERS_PER_PAGE);
  const toggleSort = (key) => setSort((s) => s.key === key ? { key, dir: s.dir === "asc" ? "desc" : "asc" } : { key, dir: (key === "name" || key === "region") ? "asc" : "desc" });

  const cols = [
    { key: "name", label: "Emitent", num: false },
    { key: "region", label: "Kraj", num: false },
    { key: "bondCount", label: "Schválených emisí", num: true },
    { key: "founded", label: "Založeno", num: true },
    { key: "isSPV", label: "SPV", num: false },
  ];

  return (
    <div className="screen" data-screen-label="Seznam emitentů">
      <div className="page-hero">
        <div className="container container-wide" style={{ padding: "32px 24px 28px" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Registr ČNB · {window.ISSUERS.length} emitentů</div>
          <h1 style={{ fontSize: 32 }}>Emitenti</h1>
          <p style={{ color: "var(--ink-2)", marginTop: 10, maxWidth: 620, fontSize: 16 }}>
            Kdo za dluhopisy stojí. Sektor, sídlo, počet emisí a profil každé společnosti, včetně toho, co dělá a jakou má strategii.
          </p>
        </div>
      </div>

      <div className="container container-wide" style={{ padding: "24px 24px 64px" }}>
        <div className="list-toolbar">
          <div style={{ position: "relative", flex: "1 1 220px", maxWidth: 300 }}>
            <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", color: "var(--faint)" }}><Icon name="search" size={16} /></span>
            <input className="input" placeholder="Hledat emitenta, IČO…" value={filters.search} onChange={(e) => setF({ search: e.target.value })} style={{ paddingLeft: 34 }} />
          </div>
          <select className="select" style={{ width: "auto", minWidth: 140 }} value={filters.region} onChange={(e) => setF({ region: e.target.value })}>
            <option value="">Celá ČR</option>
            {window.KRAJE.map((k) => <option key={k} value={k}>{k}</option>)}
          </select>
          <div className="seg">
            {[["vse", "Vše"], ["ne", "Provozní"], ["ano", "SPV"]].map(([v, l]) => (
              <button key={v} className={filters.spv === v ? "on" : ""} onClick={() => setF({ spv: v })}>{l}</button>
            ))}
          </div>
          <span style={{ marginLeft: "auto", fontSize: 13.5, color: "var(--muted)" }}><b className="num" style={{ color: "var(--ink)" }}>{sorted.length}</b> emitentů</span>
        </div>

        <div className="table-wrap">
          <table className="data">
            <thead>
              <tr>
                {cols.map((c) => (
                  <th key={c.key} className={"sortable" + (c.num ? " num-col" : "") + (sort.key === c.key ? " sorted" : "")} onClick={() => toggleSort(c.key)}>
                    <span className="th-inner">{c.label}<span className="sort-caret"><Icon name={sort.key === c.key ? (sort.dir === "asc" ? "caretUp" : "caretDown") : "chevDown"} size={13} /></span></span>
                  </th>
                ))}
                <th style={{ textAlign: "right" }}>Akce</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((it) => (
                <tr key={it.id}>
                  <td>
                    <div className="cell-stack">
                      <span className="emitent-name" onClick={() => go("detail", { id: it.id })}>{it.shortName}</span>
                      <span className="emitent-sub">{it.ico ? "IČO " + it.ico : "IČO neuvedeno"}{it.city ? " · " + it.city : ""}</span>
                    </div>
                  </td>
                  <td style={{ color: "var(--ink-2)" }}>{it.region || "–"}</td>
                  <td className="col-num" style={{ color: "var(--ink)" }}>{it.bondCount}</td>
                  <td className="col-num" style={{ color: "var(--ink-2)" }}>{it.founded || "–"}</td>
                  <td><SpvBadge value={it.isSPV} /></td>
                  <td>
                    <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
                      <button className="btn btn-ghost btn-sm" onClick={() => go("detail", { id: it.id })}>Profil</button>
                    </div>
                  </td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={6} style={{ textAlign: "center", padding: "56px 16px", color: "var(--muted)" }}>Žádný emitent neodpovídá filtrům.</td></tr>}
            </tbody>
          </table>
        </div>

        {pageCount > 1 && (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 18, flexWrap: "wrap", gap: 12 }}>
            <span style={{ fontSize: 13, color: "var(--muted)" }}>Strana {curPage} z {pageCount}</span>
            <Pager page={curPage} pageCount={pageCount} setPage={setPage} />
          </div>
        )}
        <div style={{ marginTop: 28 }}><Disclaimer /></div>
      </div>
    </div>
  );
}

Object.assign(window, { IssuersScreen });
