// Shared UI primitives for the Assurix directory prototype.
// Brand tokens locked to the real Assurix site (Montserrat, #071e47 navy, etc.)

const { useMemo } = React;

// Brand tokens
window.ASX = {
  navy: "#071e47",
  blue: "#0b3885",
  teal: "#2a9d8f",
  tealDark: "#238477",
  lime: "#b8d645",       // hsl(75 70% 45%)
  limeContrast: "#9fba3d",
  ink: "#071e47",
  muted: "#6b7280",
  line: "#e5e7eb",
  bg: "#ffffff",
  bgSoft: "#f5f7fa",
  bgMuted: "#f3f4f6",
  font: "'Montserrat', -apple-system, BlinkMacSystemFont, sans-serif",
  mono: "'JetBrains Mono', ui-monospace, monospace",
};

// ---------- Hex grid background ---------------------------------------------
function HexPattern({ opacity = 0.06, stroke = "#071e47", id = "hex-bg" }) {
  return (
    <svg aria-hidden="true" width="100%" height="100%" style={{position:"absolute", inset:0, pointerEvents:"none"}}>
      <defs>
        <pattern id={id} x="0" y="0" width="56" height="48.5" patternUnits="userSpaceOnUse">
          <path d="M14 0 L42 0 L56 24.25 L42 48.5 L14 48.5 L0 24.25 Z" fill="none" stroke={stroke} strokeWidth="1" opacity={opacity}/>
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill={`url(#${id})`}/>
    </svg>
  );
}

// ---------- Logo (wordmark) --------------------------------------------------
function Logo({ color = "#071e47", size = 22 }) {
  // Assurix uses a plain wordmark in the nav.
  return (
    <span style={{
      fontFamily: window.ASX.font,
      fontWeight: 700,
      fontSize: size,
      letterSpacing: "-0.02em",
      color,
    }}>Assurix</span>
  );
}

// ---------- BlockMark trustmark ---------------------------------------------
// Hex-shaped badge. For the canonical "Assurix" mark, renders the real
// PNG asset. For per-MSP badges, renders an SVG with the MSP's name
// slotted into the same template.
function BlockMark({ variant = "trusted", size = 200, name = "Assurix", verified = true, blockmarkId }) {
  const isTrusted = variant === "trusted";
  const lime = window.ASX.lime;
  const teal = window.ASX.teal;

  // Real asset aspect ratio: 2048x2563 ≈ 0.799 w/h → h = w * 1.2515
  const svgW = size;
  const svgH = size * 1.2515;

  // Trusted tier — always the canonical PNG trustmark
  if (isTrusted) {
    return (
      <div style={{position:"relative", width:svgW, height:svgH + (blockmarkId ? 24 : 0), flexShrink:0}}>
        <img src={(window.__resources && window.__resources.trustmarkImg) || "trustmark.png"} alt="Assurix Trusted MSP"
             width={svgW} height={svgH}
             style={{display:"block", filter:"drop-shadow(0 14px 30px rgba(7,30,71,0.25))"}}/>
        {blockmarkId && (
          <div style={{
            position:"absolute", bottom:0, left:0, right:0, textAlign:"center",
            fontFamily: window.ASX.mono,
            fontSize: Math.max(9, size * 0.052),
            color:"#6b7280", letterSpacing:"0.04em"
          }}>{blockmarkId}</div>
        )}
      </div>
    );
  }

  // On the Journey tier — use the canonical Journey image
  return (
    <div style={{position:"relative", width:svgW, height:svgH + (blockmarkId ? 24 : 0), flexShrink:0}}>
      <img src={(window.__resources && window.__resources.journeyTrustmarkImg) || "journey-trustmark.jpg"}
           alt="Assurix On the Journey"
           width={svgW} height={svgH}
           style={{display:"block", filter:"drop-shadow(0 14px 30px rgba(7,30,71,0.25))"}}/>
      {blockmarkId && (
        <div style={{
          position:"absolute", bottom:0, left:0, right:0, textAlign:"center",
          fontFamily: window.ASX.mono,
          fontSize: Math.max(9, size * 0.052),
          color:"#6b7280", letterSpacing:"0.04em"
        }}>{blockmarkId}</div>
      )}
    </div>
  );
}

// --- (legacy SVG BlockMark — kept below in case we need the procedural variant) ---
function _BlockMarkSVG({ variant, size, svgW, svgH, verified, blockmarkId, lime, teal, isTrusted }) {
  return (
    <div style={{position:"relative", width:svgW, height:svgH + (blockmarkId ? 24 : 0), flexShrink:0}}>
      <svg viewBox="0 0 200 230" width={svgW} height={svgH} style={{display:"block", filter:"drop-shadow(0 14px 30px rgba(7,30,71,0.25))"}}>
        <defs>
          {/* Navy body gradient */}
          <linearGradient id={`bm-body-${variant}-${size}`} x1="0.2" y1="0" x2="0.8" y2="1">
            <stop offset="0" stopColor="#13275a"/>
            <stop offset="1" stopColor="#061533"/>
          </linearGradient>
          {/* Silver/metallic band gradient */}
          <linearGradient id={`bm-band-${variant}-${size}`} x1="0" y1="0.5" x2="1" y2="0.5">
            <stop offset="0"    stopColor="#9aa3b2"/>
            <stop offset="0.15" stopColor="#e5e8ee"/>
            <stop offset="0.45" stopColor="#ffffff"/>
            <stop offset="0.55" stopColor="#ffffff"/>
            <stop offset="0.85" stopColor="#e5e8ee"/>
            <stop offset="1"    stopColor="#9aa3b2"/>
          </linearGradient>
          {/* Lime → teal corner accents */}
          <linearGradient id={`bm-cornerL-${variant}-${size}`} x1="0" y1="1" x2="1" y2="0">
            <stop offset="0"   stopColor={lime}/>
            <stop offset="0.6" stopColor={lime} stopOpacity="0.6"/>
            <stop offset="1"   stopColor={lime} stopOpacity="0"/>
          </linearGradient>
          <linearGradient id={`bm-cornerR-${variant}-${size}`} x1="1" y1="1" x2="0" y2="0">
            <stop offset="0"   stopColor={teal}/>
            <stop offset="0.6" stopColor={teal} stopOpacity="0.6"/>
            <stop offset="1"   stopColor={teal} stopOpacity="0"/>
          </linearGradient>
          {/* Hex clip */}
          <clipPath id={`bm-clip-${variant}-${size}`}>
            <path d="M100 8 L186 56 L186 158 L100 206 L14 158 L14 56 Z"/>
          </clipPath>
        </defs>

        {/* body */}
        <g clipPath={`url(#bm-clip-${variant}-${size})`}>
          <rect x="0" y="0" width="200" height="230" fill={`url(#bm-body-${variant}-${size})`}/>

          {/* PCB circuit traces — thin, pale blue, with small ring junctions */}
          <g stroke="#4a6ea8" strokeWidth="0.7" fill="none" opacity="0.75" strokeLinecap="round">
            <path d="M12 38 H58 L66 46 H95"/>
            <path d="M8 62 H40 L48 70 H88"/>
            <path d="M8 86 H28 L36 94 H72"/>
            <path d="M10 112 H50 L58 104 H100"/>
            <path d="M12 138 H48"/>
            <path d="M14 160 H60 L68 168 H98"/>
            <path d="M105 46 H140 L148 38 H192"/>
            <path d="M112 70 H150 L158 62 H192"/>
            <path d="M128 94 H164 L172 86 H194"/>
            <path d="M100 118 H152 L160 110 H192"/>
            <path d="M140 138 H190"/>
            <path d="M102 168 H145 L153 160 H190"/>
            {/* verticals */}
            <path d="M28 20 V46 L36 54 V78"/>
            <path d="M58 14 V38 L66 46 V72"/>
            <path d="M140 14 V38 L148 46 V76"/>
            <path d="M170 20 V46 L178 54 V80"/>
            <path d="M36 104 V140"/>
            <path d="M70 126 V170"/>
            <path d="M130 126 V170"/>
            <path d="M166 108 V148"/>
          </g>
          {/* junction rings (small circles on trace ends) */}
          <g stroke="#4a6ea8" strokeWidth="0.7" fill="#061533" opacity="0.85">
            <circle cx="28" cy="20" r="1.6"/>
            <circle cx="58" cy="14" r="1.6"/>
            <circle cx="140" cy="14" r="1.6"/>
            <circle cx="170" cy="20" r="1.6"/>
            <circle cx="36" cy="78" r="1.6"/>
            <circle cx="66" cy="72" r="1.6"/>
            <circle cx="148" cy="76" r="1.6"/>
            <circle cx="178" cy="80" r="1.6"/>
            <circle cx="36" cy="140" r="1.6"/>
            <circle cx="70" cy="170" r="1.6"/>
            <circle cx="130" cy="170" r="1.6"/>
            <circle cx="166" cy="148" r="1.6"/>
          </g>

          {/* Lime/teal accents on bottom-left and bottom-right facets */}
          <path d="M14 158 L100 206 L100 178 L22 136 Z" fill={`url(#bm-cornerL-${variant}-${size})`}/>
          <path d="M186 158 L100 206 L100 178 L178 136 Z" fill={`url(#bm-cornerR-${variant}-${size})`}/>
        </g>

        {/* outer hex stroke */}
        <path d="M100 8 L186 56 L186 158 L100 206 L14 158 L14 56 Z"
              fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="1"/>

        {/* Check ring — transparent interior, teal stroke */}
        {verified && (
          <g transform="translate(100, 48)">
            <circle r="20" fill="none" stroke={teal} strokeWidth="4.5"/>
            <path d="M-9 1 L-2 9 L11 -7" fill="none" stroke="#fff" strokeWidth="5"
                  strokeLinecap="round" strokeLinejoin="round"/>
          </g>
        )}

        {/* Wordmark — always "Assurix" */}
        <text x="100" y="110" textAnchor="middle"
              fontFamily={window.ASX.font} fontWeight="800"
              fontSize="34" fill="#fff" letterSpacing="-0.03em">
          Assurix
        </text>

        {/* Silver tier band with subtle slant */}
        <g>
          <path d="M10 128 L192 124 L194 158 L8 162 Z"
                fill={`url(#bm-band-${variant}-${size})`}/>
          <path d="M10 128 L192 124 L194 158 L8 162 Z"
                fill="none" stroke="rgba(0,0,0,0.08)" strokeWidth="0.6"/>
          <text x="100" y="150" textAnchor="middle"
                fontFamily={window.ASX.font} fontWeight="800"
                fontSize="18" fill="#071e47" letterSpacing="-0.01em">
            {isTrusted ? "Trusted MSP" : "On the Journey"}
          </text>
        </g>
      </svg>
      {blockmarkId && (
        <div style={{
          position:"absolute", bottom:0, left:0, right:0, textAlign:"center",
          fontFamily: window.ASX.mono,
          fontSize: Math.max(9, size * 0.052),
          color:"#6b7280", letterSpacing:"0.04em"
        }}>{blockmarkId}</div>
      )}
    </div>
  );
}

function truncateName(name, max) {
  if (!name) return "";
  if (name.length <= max) return name;
  return name.slice(0, max - 1) + "…";
}

// Baseline for the MSP name — shifts up slightly when font is large so it
// doesn't collide with the silver band.
function nameBaseline(name) {
  const n = (name || "").length;
  if (n <= 9)  return 108;
  if (n <= 13) return 110;
  return 112;
}

// Scale the MSP name to fit inside the hex body (~180 usable px of width).
function nameFontSize(name) {
  const n = (name || "").length;
  if (n <= 6)  return 40;
  if (n <= 8)  return 34;
  if (n <= 10) return 28;
  if (n <= 13) return 24;
  if (n <= 16) return 20;
  if (n <= 19) return 17;
  return 15;
}

// ---------- Status chip -----------------------------------------------------
// Mirrors the real product statuses: ACTIVE, AT_RISK, SUSPENDED, EXPIRED,
// plus ON_JOURNEY for MSPs still being onboarded.
function StatusBadge({ status, small = false }) {
  const map = {
    trusted:    { bg:"#dcfce7", fg:"#166534", dot:"#16a34a", label:"Verified Active" },
    journey:    { bg:"#f4fbe0", fg:"#3f5f07", dot:"#84a516", label:"On the Journey" },
    at_risk:    { bg:"#fef3c7", fg:"#854d0e", dot:"#d97706", label:"At Risk" },
    suspended:  { bg:"#fee2e2", fg:"#991b1b", dot:"#dc2626", label:"Suspended" },
    expired:    { bg:"#f3f4f6", fg:"#4b5563", dot:"#9ca3af", label:"Expired" },
  };
  const s = map[status] || map.trusted;
  return (
    <span style={{
      display:"inline-flex", alignItems:"center", gap:6,
      padding: small ? "3px 9px" : "5px 11px",
      borderRadius: 6,
      background: s.bg,
      color: s.fg,
      fontSize: small ? 11 : 12,
      fontWeight:600,
      letterSpacing:"0",
      whiteSpace:"nowrap",
      fontFamily: window.ASX.font,
    }}>
      <span style={{width:6, height:6, borderRadius:99, background:s.dot}}/>
      {s.label}
    </span>
  );
}

// Back-compat export (older files may still reference StageChip)
const StageChip = StatusBadge;

// ---------- Founding 50 badge ----------------------------------------------
// Small lime chip with a star glyph. Native title tooltip on hover.
function FoundingBadge({ small = false }) {
  return (
    <span title="One of the first 50 MSPs to sign up to Assurix — a founding member of the trust network."
      style={{
        display:"inline-flex", alignItems:"center", gap:6,
        padding: small ? "3px 8px 3px 6px" : "4px 10px 4px 8px",
        borderRadius: 6,
        background: "linear-gradient(180deg, #F3FACC 0%, #E6F3A3 100%)",
        color: "#3F5F07",
        fontSize: small ? 11 : 12,
        fontWeight: 700,
        letterSpacing: "0.01em",
        whiteSpace: "nowrap",
        border: "1px solid #C8DE7A",
        fontFamily: window.ASX.font,
        cursor: "help",
      }}>
      <svg width={small ? 10 : 12} height={small ? 10 : 12} viewBox="0 0 24 24" fill="#84a516">
        <path d="M12 2l2.8 6.5 7.2.6-5.5 4.7 1.7 7-6.2-3.8-6.2 3.8 1.7-7L2 9.1l7.2-.6z"/>
      </svg>
      Founding 50
    </span>
  );
}

// ---------- Misc icons ------------------------------------------------------
function Icon({ name, size = 16, color = "currentColor", strokeWidth = 1.8 }) {
  const p = { width:size, height:size, viewBox:"0 0 24 24", fill:"none", stroke:color, strokeWidth, strokeLinecap:"round", strokeLinejoin:"round"};
  switch (name) {
    case "search": return (<svg {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>);
    case "arrow-right": return (<svg {...p}><path d="M5 12h14"/><path d="m13 6 6 6-6 6"/></svg>);
    case "arrow-up-right": return (<svg {...p}><path d="M7 17 17 7"/><path d="M8 7h9v9"/></svg>);
    case "check": return (<svg {...p}><path d="m5 12 5 5 9-11"/></svg>);
    case "shield": return (<svg {...p}><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z"/></svg>);
    case "map-pin": return (<svg {...p}><path d="M12 22s-7-6.5-7-12a7 7 0 1 1 14 0c0 5.5-7 12-7 12Z"/><circle cx="12" cy="10" r="2.5"/></svg>);
    case "users": return (<svg {...p}><path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/><circle cx="10" cy="8" r="4"/><path d="M21 21v-2a4 4 0 0 0-3-3.87"/><path d="M17 4a4 4 0 0 1 0 8"/></svg>);
    case "building": return (<svg {...p}><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M9 8h.01M9 12h.01M9 16h.01M15 8h.01M15 12h.01M15 16h.01"/></svg>);
    case "calendar": return (<svg {...p}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>);
    case "phone": return (<svg {...p}><path d="M22 16.9v2.6a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 3.8 2 2 0 0 1 4.1 1.6h2.6a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.7a2 2 0 0 1-.5 2.1L7.6 9.3a16 16 0 0 0 6 6l1.2-1.2a2 2 0 0 1 2.1-.5c.9.3 1.8.5 2.7.6A2 2 0 0 1 22 16.9Z"/></svg>);
    case "mail": return (<svg {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/></svg>);
    case "globe": return (<svg {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14 0 18M12 3c-3 3.5-3 14 0 18"/></svg>);
    case "filter": return (<svg {...p}><path d="M3 5h18M6 12h12M10 19h4"/></svg>);
    case "grid": return (<svg {...p}><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>);
    case "list": return (<svg {...p}><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/></svg>);
    case "map": return (<svg {...p}><path d="M9 3 3 5v16l6-2 6 2 6-2V3l-6 2-6-2Z"/><path d="M9 3v16M15 5v16"/></svg>);
    case "chevron-down": return (<svg {...p}><path d="m6 9 6 6 6-6"/></svg>);
    case "chevron-right": return (<svg {...p}><path d="m9 6 6 6-6 6"/></svg>);
    case "x": return (<svg {...p}><path d="M6 6l12 12M18 6 6 18"/></svg>);
    case "sliders": return (<svg {...p}><path d="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6"/></svg>);
    case "external": return (<svg {...p}><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5"/></svg>);
    case "copy": return (<svg {...p}><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>);
    case "trending-up": return (<svg {...p}><path d="m22 7-9 9-4-4-7 7"/><path d="M15 7h7v7"/></svg>);
    case "zap": return (<svg {...p}><path d="M13 2 3 14h8l-1 8 10-12h-8l1-8Z"/></svg>);
    case "share": return (<svg {...p}><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"/></svg>);
    case "alert": return (<svg {...p}><path d="M12 2 2 22h20Z"/><path d="M12 10v4M12 18h.01"/></svg>);
    case "help": return (<svg {...p}><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-.8.6-1.5 1.2-1.5 2.5M12 17h.01"/></svg>);
    default: return null;
  }
}

// ---------- Logo placeholder for MSP ----------------------------------------
function MspMark({ msp, size = 44, rounded = 10 }) {
  const initials = msp.name.split(" ").map(w=>w[0]).slice(0,2).join("");
  return (
    <div style={{
      width:size, height:size, borderRadius:rounded,
      background: msp.color,
      color:"#fff",
      display:"flex", alignItems:"center", justifyContent:"center",
      fontFamily: window.ASX.font, fontWeight:700,
      fontSize: size * 0.38,
      letterSpacing:"-0.02em",
      flexShrink:0,
    }}>{initials}</div>
  );
}

Object.assign(window, { HexPattern, Logo, BlockMark, StatusBadge, StageChip, Icon, MspMark, FoundingBadge });
