// eid-listing-page.jsx
// "All eID integrations" listing page.
// Depends on: window.ccEidData (eid-data.jsx), Icon (nav.jsx)

function EidListingPage() {
  const data = window.ccEidData || [];
  const [search, setSearch] = React.useState("");
  const [activeRegion, setActiveRegion] = React.useState("All");

  // Collect unique regions in a sensible display order
  const regionOrder = [
    "Nordics", "Baltics", "DACH", "Benelux", "UK & Ireland",
    "Southern Europe", "Eastern Europe", "Americas", "Asia Pacific", "Global",
  ];
  const presentRegions = regionOrder.filter((r) =>
    data.some((d) => d.region === r)
  );
  const regions = ["All", ...presentRegions];

  // Filter
  const filtered = data.filter((eid) => {
    const s = search.toLowerCase();
    
    // Check name match
    const nameMatch = eid.name.toLowerCase().includes(s);
    
    // Check coverage match (country code or country name)
    const coverageMatch = eid.coverage.some((code) => {
      const codeMatch = code.toLowerCase() === s || code.toLowerCase().includes(s);
      const countryName = CC_NAMES_LISTING[code] || "";
      const countryNameMatch = countryName.toLowerCase().includes(s);
      return codeMatch || countryNameMatch;
    });

    const matchSearch = !search || nameMatch || coverageMatch;
    const matchRegion = activeRegion === "All" || eid.region === activeRegion;
    return matchSearch && matchRegion;
  });


  // Group by region when "All" is selected, otherwise flat list
  const grouped = React.useMemo(() => {
    if (activeRegion !== "All") {
      return { [activeRegion]: filtered };
    }
    const g = {};
    regionOrder.forEach((r) => {
      const items = filtered.filter((d) => d.region === r);
      if (items.length > 0) g[r] = items;
    });
    return g;
  }, [filtered, activeRegion]);

  return (
    <div>
      {/* ── Hero ─────────────────────────────────────────────────────────── */}
      <section
        className="section"
        style={{
          background: "var(--bg-soft)",
          borderBottom: "1px solid var(--line)",
          paddingBottom: 56,
        }}
      >
        <div className="container">
          {/* Breadcrumb */}
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 28, fontSize: 13, color: "var(--ink-4)" }}>
            <a href="/esignature" style={{ color: "var(--ink-3)", textDecoration: "none", fontWeight: 500 }}
              onMouseEnter={(e) => (e.currentTarget.style.color = "var(--accent)")}
              onMouseLeave={(e) => (e.currentTarget.style.color = "var(--ink-3)")}
            >eSignature</a>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ flexShrink: 0 }}>
              <polyline points="9 18 15 12 9 6" />
            </svg>
            <span className="tag tag-purple" style={{ margin: 0, padding: "2px 10px", fontSize: 12.5 }}>eID Integrations</span>
          </div>

          <div style={{ maxWidth: 680 }}>
            <span className="eyebrow">eID Integrations</span>
            <h1
              className="h-section"
              style={{
                fontSize: "clamp(38px, 4.5vw, 62px)",
                marginTop: 16,
                marginBottom: 20,
                letterSpacing: "-0.032em",
              }}
            >
              60+ eIDs supported.{" "}
              <em>Globally.</em>
            </h1>
            <p className="lede" style={{ maxWidth: 52 + "ch" }}>
              ContractControl connects to the eID your counterparty already
              uses, from Swedish BankID and Norway BankID to SPID, Smart-ID,
              and beyond. No new apps, no friction, just signatures.
            </p>
          </div>
        </div>
      </section>

      {/* ── Search + Filter ──────────────────────────────────────────────── */}
      <section
        className="section"
        style={{ paddingTop: 40, paddingBottom: 0 }}
      >
        <div className="container">
          {/* Search */}
          <div style={{ position: "relative", maxWidth: 400, marginBottom: 28 }}>
            <span
              style={{
                position: "absolute",
                left: 14,
                top: "50%",
                transform: "translateY(-50%)",
                color: "var(--ink-4)",
                pointerEvents: "none",
                display: "grid",
                placeItems: "center",
              }}
            >
              <svg
                width="15"
                height="15"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="11" cy="11" r="7" />
                <line x1="21" y1="21" x2="16.65" y2="16.65" />
              </svg>
            </span>
            <input
              type="text"
              placeholder="Search eIDs…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{
                width: "100%",
                height: 42,
                padding: "0 16px 0 40px",
                borderRadius: 999,
                border: "1px solid var(--line-strong)",
                background: "var(--bg-elevated)",
                fontFamily: "inherit",
                fontSize: 14,
                color: "var(--ink-1)",
                outline: "none",
                transition: "border-color 140ms ease",
              }}
              onFocus={(e) => (e.target.style.borderColor = "var(--accent)")}
              onBlur={(e) => (e.target.style.borderColor = "var(--line-strong)")}
            />
          </div>

          {/* Region pills */}
          <div
            style={{
              display: "flex",
              flexWrap: "wrap",
              gap: 8,
              marginBottom: 40,
            }}
          >
            {regions.map((r) => (
              <button
                key={r}
                onClick={() => setActiveRegion(r)}
                style={{
                  height: 34,
                  padding: "0 16px",
                  borderRadius: 999,
                  border: "1px solid",
                  borderColor:
                    activeRegion === r ? "var(--accent)" : "var(--line-strong)",
                  background:
                    activeRegion === r ? "var(--accent-soft)" : "var(--bg-elevated)",
                  color:
                    activeRegion === r ? "var(--accent-ink)" : "var(--ink-2)",
                  fontFamily: "inherit",
                  fontSize: 13,
                  fontWeight: activeRegion === r ? 500 : 400,
                  cursor: "pointer",
                  transition: "all 140ms ease",
                  whiteSpace: "nowrap",
                }}
              >
                {r}
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* ── Results ──────────────────────────────────────────────────────── */}
      <section className="section" style={{ paddingTop: 0, paddingBottom: 80 }}>
        <div className="container">
          {Object.keys(grouped).length === 0 && (
            <div
              style={{
                textAlign: "center",
                padding: "80px 0",
                color: "var(--ink-4)",
                fontSize: 15,
              }}
            >
              No eIDs found matching "{search}".
            </div>
          )}

          {Object.entries(grouped).map(([region, eids]) => (
            <div key={region} style={{ marginBottom: 56 }}>
              {activeRegion === "All" && (
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 12,
                    marginBottom: 20,
                    paddingBottom: 12,
                    borderBottom: "1px solid var(--line)",
                  }}
                >
                  <h2
                    style={{
                      margin: 0,
                      fontSize: 18,
                      fontWeight: 500,
                      letterSpacing: "-0.015em",
                      color: "var(--ink-1)",
                    }}
                  >
                    {region}
                  </h2>
                  <span
                    style={{
                      fontSize: 12,
                      color: "var(--ink-4)",
                      background: "var(--bg-soft)",
                      border: "1px solid var(--line)",
                      borderRadius: 999,
                      padding: "2px 10px",
                    }}
                  >
                    {eids.length}
                  </span>
                </div>
              )}

              <div
                style={{
                  display: "grid",
                  gridTemplateColumns:
                    "repeat(auto-fill, minmax(280px, 1fr))",
                  gap: 16,
                }}
              >
                {eids.map((eid) => (
                  <EidCard key={eid.slug} eid={eid} />
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

function countryFlag(code) {
  return code.toUpperCase().replace(/./g, (c) =>
    String.fromCodePoint(c.charCodeAt(0) + 0x1F1A5)
  );
}

const CC_NAMES_LISTING = {
  // Nordics & Baltics
  SE: "Sweden", NO: "Norway", DK: "Denmark", FI: "Finland", IS: "Iceland",
  EE: "Estonia", LV: "Latvia", LT: "Lithuania", GL: "Greenland", AX: "Åland",
  // Western & Southern Europe
  DE: "Germany", AT: "Austria", CH: "Switzerland", LI: "Liechtenstein",
  BE: "Belgium", NL: "Netherlands", LU: "Luxembourg", FR: "France",
  GB: "United Kingdom", IE: "Ireland", GG: "Guernsey", IM: "Isle of Man", JE: "Jersey",
  IT: "Italy", PT: "Portugal", ES: "Spain", GR: "Greece",
  AD: "Andorra", MC: "Monaco", SM: "San Marino", VA: "Vatican City",
  // Eastern Europe & Balkans
  HR: "Croatia", SI: "Slovenia", MT: "Malta", CY: "Cyprus", PL: "Poland",
  CZ: "Czechia", SK: "Slovakia", HU: "Hungary", RO: "Romania", BG: "Bulgaria",
  UA: "Ukraine", RS: "Serbia", AL: "Albania", MK: "North Macedonia",
  BA: "Bosnia and Herzegovina", ME: "Montenegro", MD: "Moldova",
  AM: "Armenia", AZ: "Azerbaijan", BY: "Belarus", GE: "Georgia",
  KZ: "Kazakhstan", RU: "Russia", XK: "Kosovo",
  // Americas
  US: "United States", CA: "Canada", BR: "Brazil", MX: "Mexico",
  AR: "Argentina", CL: "Chile", CO: "Colombia", CR: "Costa Rica",
  DO: "Dominican Republic", EC: "Ecuador", PA: "Panama", PE: "Peru",
  UY: "Uruguay", VE: "Venezuela",
  // Asia Pacific & Africa
  AU: "Australia", NZ: "New Zealand", IN: "India", JP: "Japan",
  KR: "South Korea", SG: "Singapore", CN: "China", MY: "Malaysia",
  ID: "Indonesia", IL: "Israel", AE: "United Arab Emirates", SA: "Saudi Arabia",
  QA: "Qatar", TR: "Turkey", ZA: "South Africa", KE: "Kenya",
  BD: "Bangladesh", EG: "Egypt", PK: "Pakistan", TW: "Taiwan",
  TH: "Thailand", VN: "Vietnam",
  // Global
  WORLD: "Global"
};


function FlagWithTooltip({ code }) {
  const [visible, setVisible] = React.useState(false);
  const name = CC_NAMES_LISTING[code] || code;
  return (
    <span
      style={{ position: "relative", display: "inline-flex", alignItems: "center" }}
      onMouseEnter={() => setVisible(true)}
      onMouseLeave={() => setVisible(false)}
    >
      <span style={{ fontSize: 14, lineHeight: 1, cursor: "default" }}>
        {code === "WORLD" ? "🌐" : countryFlag(code)}
      </span>
      {visible && (
        <span style={{
          position: "absolute",
          bottom: "calc(100% + 6px)",
          left: "50%",
          transform: "translateX(-50%)",
          background: "var(--ink-1)",
          color: "#fff",
          fontSize: 11,
          fontWeight: 500,
          whiteSpace: "nowrap",
          padding: "3px 8px",
          borderRadius: 5,
          pointerEvents: "none",
          zIndex: 10,
        }}>
          {name}
        </span>
      )}
    </span>
  );
}

function EidCard({ eid }) {
  const showFlags = eid.coverage[0] !== "WORLD" && eid.coverage.length <= 6;
  const overflowCount = eid.coverage.length > 6 ? eid.coverage.length - 5 : 0;
  const visibleCodes = overflowCount > 0 ? eid.coverage.slice(0, 5) : eid.coverage;

  const signColor = { bg: "var(--accent-soft)", color: "var(--accent)", border: "rgba(110,86,207,0.22)" };
  const authColor = { bg: "rgba(22,163,74,0.08)", color: "#166534", border: "rgba(22,163,74,0.25)" };

  return (
    <a
      href={`/esignature/eID-integrations/${eid.slug}`}
      className="card"
      style={{
        padding: "20px 22px",
        display: "flex",
        flexDirection: "column",
        gap: 12,
        textDecoration: "none",
        transition: "border-color 160ms ease, transform 160ms ease, box-shadow 160ms ease",
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.borderColor = "var(--ink-5)";
        e.currentTarget.style.transform = "translateY(-2px)";
        e.currentTarget.style.boxShadow = "0 8px 24px -8px rgba(14,14,16,0.10)";
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.borderColor = "var(--line)";
        e.currentTarget.style.transform = "translateY(0)";
        e.currentTarget.style.boxShadow = "none";
      }}
    >
      {/* Top row: name + region */}
      <div
        style={{
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          gap: 8,
        }}
      >
        <div
          style={{
            fontSize: 15,
            fontWeight: 500,
            color: "var(--ink-1)",
            lineHeight: 1.3,
          }}
        >
          {eid.name}
        </div>
        <span
          style={{
            flexShrink: 0,
            fontSize: 10.5,
            fontWeight: 500,
            letterSpacing: "0.06em",
            textTransform: "uppercase",
            color: "var(--ink-4)",
            background: "var(--bg-soft)",
            border: "1px solid var(--line)",
            borderRadius: 999,
            padding: "2px 9px",
            whiteSpace: "nowrap",
          }}
        >
          {eid.region}
        </span>
      </div>

      {/* Badges row */}
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        {/* Sign badge, always shown */}
        <span style={{ fontSize: 11.5, fontWeight: 500, padding: "3px 10px", borderRadius: 999, background: signColor.bg, color: signColor.color, border: `1px solid ${signColor.border}` }}>
          Sign
        </span>
        {/* Auth badge, only when supported */}
        {eid.auth && (
          <span style={{ fontSize: 11.5, fontWeight: 500, padding: "3px 10px", borderRadius: 999, background: authColor.bg, color: authColor.color, border: `1px solid ${authColor.border}` }}>
            Auth
          </span>
        )}

        {/* Coverage */}
        {eid.coverage[0] === "WORLD" ? (
          <span style={{ fontSize: 13, color: "var(--ink-4)" }}>🌐 Global</span>
        ) : (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
            {visibleCodes.map((cc) => <FlagWithTooltip key={cc} code={cc} />)}
            {overflowCount > 0 && (
              <span style={{ fontSize: 11, color: "var(--ink-4)", marginLeft: 2 }}>+{overflowCount}</span>
            )}
          </span>
        )}
      </div>

      {/* Link cue */}
      <div
        style={{
          marginTop: "auto",
          display: "inline-flex",
          alignItems: "center",
          gap: 5,
          fontSize: 12.5,
          fontWeight: 500,
          color: "var(--accent)",
        }}
      >
        Learn more <Icon name="arrow" size={12} />
      </div>
    </a>
  );
}

Object.assign(window, { EidListingPage, EidCard });
