// Signatory wall — individuals / organizations / nations, with live count.

// One organization card: favicon logo pulled from the org's domain, with a
// monogram fallback when there's no site or the logo fails to load.
function OrgCard({ org, shortCountry }) {
  const [logoOk, setLogoOk] = React.useState(true);
  let host = null;
  try { if (org.url) host = new URL(org.url).hostname; } catch (e) {}
  // A custom logo (org.logo) overrides the auto favicon.
  const logo = org.logo || (host ? `https://www.google.com/s2/favicons?domain=${host}&sz=64` : null);

  const inner = (
    <React.Fragment>
      <span className={"org-card__mark" + (org.logo && logoOk ? " org-card__mark--custom" : "")} aria-hidden="true">
        {logo && logoOk
          ? <img className="org-card__logo" src={logo} alt="" loading="lazy" onError={() => setLogoOk(false)} />
          : org.name.trim().charAt(0)}
      </span>
      <div className="org-card__body">
        <span className="org-card__name">{org.name}{org.you ? <em> · you</em> : null}</span>
        {org.country ? <span className="org-card__meta">{shortCountry(org.country)}</span> : null}
      </div>
    </React.Fragment>
  );

  const cls = "org-card" + (org.you ? " org-card--you" : "") + (org.url ? " org-card--link" : "");
  return (
    <li className={cls}>
      {org.url
        ? <a className="org-card__hit" href={org.url} target="_blank" rel="noopener noreferrer">{inner}</a>
        : inner}
    </li>
  );
}

const shortCountry = (c) => ({
  "United States of America": "United States",
  "United Kingdom": "United Kingdom",
  "Czechia (Czech Republic)": "Czechia",
}[c] || c);

function Signatories({ data, count, recent }) {
  const { Eyebrow, Button, Stat, Input } = window.IAIGADesignSystem_db07e0;
  const { Icon } = window;
  const [tab, setTab] = React.useState("individuals");
  const [expanded, setExpanded] = React.useState(false);
  const [orgExpanded, setOrgExpanded] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const [orgQuery, setOrgQuery] = React.useState("");
  const [copied, setCopied] = React.useState(false);

  const shareUrl = "https://iaiga.org";
  const shareText = "I signed the IAIGA petition calling for global AI governance. Join me — eight billion people have a stake.";
  const encodedUrl = encodeURIComponent(shareUrl);
  const encodedText = encodeURIComponent(shareText);

  const copyLink = () => {
    navigator.clipboard.writeText(shareUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const recentPeople = recent.filter((r) => r.kind !== "org");
  const recentOrgs = recent.filter((r) => r.kind === "org");
  // First 18 are hand-pinned (in data order); everyone else — including new
  // verified signatures — is merged and sorted alphabetically by name.
  const PINNED = 18;
  const sortKey = (s) => (s.name || "").normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase();
  const byName = (a, b) => sortKey(a).localeCompare(sortKey(b));
  const people = [
    ...data.signatories.slice(0, PINNED),
    ...[...data.signatories.slice(PINNED), ...recentPeople].sort(byName),
  ];
  const orgs = [...(data.organizations || []), ...recentOrgs];

  const q = query.trim().toLowerCase();
  const filtered = q
    ? people.filter((s) => (s.name + " " + (s.role || "") + " " + s.country).toLowerCase().includes(q))
    : people;
  const shownPeople = expanded ? filtered : people.slice(0, 6);

  const oq = orgQuery.trim().toLowerCase();
  const filteredOrgs = oq
    ? orgs.filter((o) => (o.name + " " + (o.country || "")).toLowerCase().includes(oq))
    : orgs;
  const shownOrgs = orgExpanded ? filteredOrgs : orgs.slice(0, 6);

  const setTabSafe = (t) => { setTab(t); setExpanded(false); setOrgExpanded(false); setQuery(""); setOrgQuery(""); };

  return (
    <section className="sigs section" id="signatories">
      <div className="wrap">
        <div className="sigs__head">
          <div>
            <Eyebrow>The signatories</Eyebrow>
            <h2 className="sigs__heading">Eight billion people have a stake. These are some of them.</h2>
          </div>
          <Stat value={count.toLocaleString()} label="signatures and counting" sub={`Target: ${data.target.toLocaleString()}`} />
        </div>

        <div className="faq-tabs" role="tablist" style={{ marginBottom: "var(--space-6)" }}>
          {[["individuals", "Individuals"], ["organizations", "Organizations"], ["nations", "Nations"]].map(([k, label]) => (
            <button key={k} role="tab" aria-selected={tab === k}
              className={"faq-tab" + (tab === k ? " is-active" : "")}
              onClick={() => setTabSafe(k)}>{label}</button>
          ))}
        </div>

        {tab === "individuals" ? (
          <React.Fragment>
            {expanded ? (
              <div className="sigs__search">
                <Icon.Search className="sigs__search-icon" aria-hidden="true" />
                <Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search signatories by name, role, or country…" aria-label="Search signatories" autoFocus />
                {q ? <span className="sigs__search-count">{filtered.length} {filtered.length === 1 ? "match" : "matches"}</span> : null}
              </div>
            ) : null}
            {shownPeople.length ? (
              <ul className={"sigs__grid" + (expanded ? " is-scroll" : "")}>
                {shownPeople.map((s, i) => (
                  <li key={s.name + i} className={"sig-card" + (s.you ? " sig-card--you" : "")}>
                    <span className="sig-card__flag" aria-hidden="true">{s.flag}</span>
                    <div className="sig-card__body">
                      <span className="sig-card__name">{s.name}{s.you ? <em> · you</em> : null}</span>
                      <span className="sig-card__role">{[s.role, shortCountry(s.country)].filter(Boolean).join(" · ")}</span>
                    </div>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="sigs__empty">No signatories match “{query}”.</p>
            )}
            <div className="sigs__more">
              <Button variant="secondary" onClick={() => { setExpanded((v) => !v); setQuery(""); }} iconRight={<Icon.ArrowRight/>}>
                {expanded ? "Show fewer" : "See all signatories"}
              </Button>
            </div>
          </React.Fragment>
        ) : null}

        {tab === "organizations" ? (
          <React.Fragment>
            {orgExpanded ? (
              <div className="sigs__search">
                <Icon.Search className="sigs__search-icon" aria-hidden="true" />
                <Input value={orgQuery} onChange={(e) => setOrgQuery(e.target.value)} placeholder="Search organizations by name or country…" aria-label="Search organizations" autoFocus />
                {oq ? <span className="sigs__search-count">{filteredOrgs.length} {filteredOrgs.length === 1 ? "match" : "matches"}</span> : null}
              </div>
            ) : null}
            {shownOrgs.length ? (
              <ul className={"org-grid" + (orgExpanded ? " is-scroll" : "")}>
                {shownOrgs.map((o, i) => (
                  <OrgCard key={o.name + i} org={o} shortCountry={shortCountry} />
                ))}
              </ul>
            ) : (
              <p className="sigs__empty">No organizations match “{orgQuery}”.</p>
            )}
            {orgs.length > 6 && (
              <div className="sigs__more">
                <Button variant="secondary" onClick={() => { setOrgExpanded((v) => !v); setOrgQuery(""); }} iconRight={<Icon.ArrowRight/>}>
                  {orgExpanded ? "Show fewer" : "See all organizations"}
                </Button>
              </div>
            )}
          </React.Fragment>
        ) : null}

        {tab === "nations" ? (
          <p className="sigs__nations">
            No nations have signed as of yet. If you represent a government or institution and
            want to engage directly, <a href="mailto:hello@iaiga.org">contact us</a>.
          </p>
        ) : null}

        <div className="sigs__share-section">
          <p className="sigs__share-label">Spread the word</p>
          <div className="share-bar">
            <button className="share-btn" onClick={copyLink}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
              {copied ? "Copied!" : "Copy link"}
            </button>
            <a className="share-btn" href={`https://x.com/intent/tweet?url=${encodedUrl}&text=${encodedText}`} target="_blank" rel="noopener noreferrer">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.736-8.854L1.254 2.25H8.08l4.257 5.629L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"/></svg>
              X
            </a>
            <a className="share-btn" href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`} target="_blank" rel="noopener noreferrer">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6zM2 9h4v12H2z"/><circle cx="4" cy="4" r="2"/></svg>
              LinkedIn
            </a>
            <a className="share-btn" href={`https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`} target="_blank" rel="noopener noreferrer">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z"/></svg>
              Facebook
            </a>
            <a className="share-btn" href={`https://wa.me/?text=${encodeURIComponent(shareText + " " + shareUrl)}`} target="_blank" rel="noopener noreferrer">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
              WhatsApp
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}
window.Signatories = Signatories;
