// ============================================================
// Shared UI primitives — buttons, inputs, icons, rings, money fns
// ============================================================

// --- helpers ---
const fmt = (n) => "$" + Math.round(n).toLocaleString();
const fmt2 = (n) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// Lucide icon helper — renders an inline SVG via the global lucide map.
const Icon = ({ name, size = 16, color, strokeWidth = 2, className = "", style }) => {
  const data = window.lucide && window.lucide.icons && window.lucide.icons[name];
  // Lucide v0.x stores arrays of [tag, attrs, children]; v latest stores objects.
  // Easier: render via element refs + createIcons.
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    ref.current.innerHTML = "";
    const i = document.createElement("i");
    i.setAttribute("data-lucide", name);
    i.style.width = size + "px";
    i.style.height = size + "px";
    if (color) i.style.color = color;
    i.style.strokeWidth = strokeWidth;
    ref.current.appendChild(i);
    if (window.lucide && window.lucide.createIcons) {
      window.lucide.createIcons({ attrs: { "stroke-width": strokeWidth } });
    }
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} className={className} style={{ display: "inline-flex", width: size, height: size, ...style }} />;
};

// Decorative concentric rings (Revenued visual device)
const Rings = ({ size = 320, palette = "teal", style }) => {
  const colors = palette === "teal" ?
  ["rgba(4,196,158,0.18)", "rgba(4,196,158,0.10)", "rgba(4,196,158,0.06)"] :
  palette === "blue" ?
  ["rgba(0,64,186,0.18)", "rgba(0,64,186,0.10)", "rgba(164,195,255,0.20)"] :
  palette === "light" ?
  ["rgba(255,255,255,0.18)", "rgba(255,255,255,0.10)", "rgba(255,255,255,0.06)"] :
  ["rgba(0,18,43,0.08)", "rgba(0,18,43,0.04)", "rgba(0,18,43,0.02)"];
  return (
    <div className="rings" style={{ width: size, height: size, ...style }}>
      <div className="ring" style={{ width: size * 0.95, height: size * 0.95, borderWidth: size * 0.06, borderColor: colors[2] }} />
      <div className="ring" style={{ width: size * 0.62, height: size * 0.62, borderWidth: size * 0.05, borderColor: colors[1] }} />
      <div className="ring" style={{ width: size * 0.30, height: size * 0.30, borderWidth: size * 0.06, borderColor: colors[0] }} />
    </div>);

};

// Button
const Button = ({ variant = "primary", size = "md", block, children, icon, iconAfter, ...rest }) => {
  const cls = `btn btn-${variant} ${size !== "md" ? "btn-" + size : ""} ${block ? "btn-block" : ""}`;
  return (
    <button className={cls} {...rest}>
      {icon && <Icon name={icon} size={16} />}
      {children}
      {iconAfter && <Icon name={iconAfter} size={16} />}
    </button>);

};

// Text input
const TextInput = ({ label, hint, prefix, value, onChange, placeholder, type = "text", id, ...rest }) =>
<div className="field">
    {label && <label className="field-label" htmlFor={id}>{label}</label>}
    <div className="field-wrap">
      {prefix && <span className="field-prefix">{prefix}</span>}
      <input
      id={id}
      className={"field-input" + (prefix ? " has-prefix" : "")}
      type={type}
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      {...rest} />
    
    </div>
    {hint && <span className="field-hint">{hint}</span>}
  </div>;


// Select
const SelectInput = ({ label, value, onChange, options, hint }) =>
<div className="field">
    {label && <label className="field-label">{label}</label>}
    <select
    className="field-input"
    value={value}
    onChange={onChange}
    style={{ appearance: "none", backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'><path d='M3 4.5l3 3 3-3' stroke='%235B5D63' stroke-width='1.6' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>\")",
      backgroundRepeat: "no-repeat", backgroundPosition: "right 12px center", paddingRight: "32px" }}>
    
      {options.map((o) => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
    </select>
    {hint && <span className="field-hint">{hint}</span>}
  </div>;


// Checkbox
const Check = ({ checked, onChange, children }) =>
<label className="checkbox">
    <input type="checkbox" checked={checked} onChange={onChange} />
    <span className="checkbox-box" />
    <span>{children}</span>
  </label>;


// Steps indicator
const Steps = ({ step, total, labels }) =>
<div className="steps">
    <span style={{ fontVariantNumeric: "tabular-nums" }}>Step {step} of {total}</span>
    <div className="steps-bar"><i style={{ width: step / total * 100 + "%" }} /></div>
    {labels && labels[step - 1] && <span style={{ color: "var(--trust-tech)" }}>{labels[step - 1]}</span>}
  </div>;


// Disclosure block — used near offers / agreements
const Disclosure = ({ children }) => <div className="disclosure">{children}</div>;

// Eyebrow
const Eyebrow = ({ children, muted }) => <div className={"eb" + (muted ? " eb-muted" : "")}>{children}</div>;

// Stat
const Stat = ({ label, value, sub, size = "md" }) =>
<div>
    <div className="stat-label">{label}</div>
    <div className={size === "xl" ? "stat-num-xl" : size === "xxl" ? "stat-num-xxl" : "stat-num"} style={{ marginTop: 6 }}>{value}</div>
    {sub && <div style={{ fontSize: 12, color: "var(--tt-60)", marginTop: 6 }}>{sub}</div>}
  </div>;


// Revenued logo (digital, light bg)
const RevenuedLogo = ({ height = 16, white = false }) =>
<img
  src={white ? "design-system/logos/Revenued_Digital_White_logo.svg" : "design-system/logos/Revenued_Digital_logo.svg"}
  alt="Revenued"
  style={{ height, display: "block" }} />;



// Cobrand strip: "Maverick Capital" + powered-by attribution
const CapitalCobrand = ({ partnerName, attribution }) => {
  const cls = attribution === "hidden" ?
  "cap-cobrand cap-cobrand--hidden" :
  attribution === "equal" ?
  "cap-cobrand cap-cobrand--equal" :
  "cap-cobrand";
  return (
    <div>
      <h1 className="cap-title">{partnerName} Capital</h1>
      <div className={cls}>
        <span>Powered by</span>
        <RevenuedLogo height={attribution === "equal" ? 18 : 12} />
      </div>
    </div>);

};

// Plaid-like mock card
const PlaidCard = ({ status = "idle", bank, onConnect }) => {
  const banks = [
  { name: "Chase", color: "#0F4D92", letter: "C" },
  { name: "Bank of America", color: "#012169", letter: "B" },
  { name: "Wells Fargo", color: "#B30019", letter: "W" },
  { name: "Capital One", color: "#003B5C", letter: "1" },
  { name: "PNC Bank", color: "#FF8200", letter: "P" },
  { name: "Citi", color: "#003C71", letter: "C" }];

  return (
    <div style={{
      background: "#fff",
      borderRadius: 16,
      boxShadow: "0 20px 60px rgba(0,18,43,0.18), 0 0 0 1px var(--border-1)",
      width: "100%",
      maxWidth: 380,
      overflow: "hidden"
    }}>
      <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-1)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 24, height: 24, borderRadius: 6, background: "#000", color: "#fff", display: "grid", placeItems: "center", fontWeight: 800, fontSize: 13 }}>P</div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Plaid <span style={{ color: "var(--tt-60)", fontWeight: 400 }}>· connecting to Revenued</span></div>
        </div>
        <Icon name="x" size={16} color="var(--tt-60)" />
      </div>
      {status === "idle" &&
      <div style={{ padding: "22px 22px 24px" }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>Select your bank</div>
          <div style={{ fontSize: 12, color: "var(--tt-60)", marginBottom: 16 }}>Your credentials are never shared with Revenued or {bank}.</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {banks.map((b) =>
          <button key={b.name} onClick={() => onConnect && onConnect(b)} style={{
            display: "flex", alignItems: "center", gap: 10, padding: "10px 12px",
            border: "1px solid var(--border-1)", borderRadius: 10, background: "#fff",
            cursor: "pointer", textAlign: "left", font: "inherit"
          }}>
                <div style={{ width: 28, height: 28, borderRadius: 6, background: b.color, color: "#fff", display: "grid", placeItems: "center", fontWeight: 800, fontSize: 13 }}>{b.letter}</div>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{b.name}</span>
              </button>
          )}
          </div>
          <div style={{ fontSize: 11, color: "var(--tt-60)", marginTop: 14, display: "flex", alignItems: "center", gap: 6 }}>
            <Icon name="lock" size={12} /> Encrypted with bank-level security.
          </div>
        </div>
      }
      {status === "loading" &&
      <div style={{ padding: "40px 22px", textAlign: "center" }}>
          <div style={{ width: 36, height: 36, borderRadius: "50%", border: "3px solid var(--gg-10)", borderTopColor: "var(--growth-galaxy)", margin: "0 auto" }} className="spin" />
          <div style={{ marginTop: 16, fontSize: 14, fontWeight: 600 }}>Connecting to your bank…</div>
          <div style={{ fontSize: 12, color: "var(--tt-60)", marginTop: 4 }}>This usually takes under 30 seconds.</div>
        </div>
      }
      {status === "success" &&
      <div style={{ padding: "28px 22px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--fp-10)", color: "var(--fp-100)", display: "grid", placeItems: "center" }}>
              <Icon name="check" size={20} strokeWidth={2.5} />
            </div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Connected</div>
              <div style={{ fontSize: 12, color: "var(--tt-60)" }}>{bank?.name || "Chase"} · Business checking ····4391</div>
            </div>
          </div>
          <div style={{ fontSize: 12, color: "var(--tt-60)" }}>Verified 90 days of deposits.</div>
        </div>
      }
    </div>);

};

// Money input with slider
const MoneySlider = ({ value, min, max, step, onChange }) => {
  const pct = (value - min) / (max - min) * 100;
  return (
    <div>
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(parseInt(e.target.value, 10))}
        style={{
          width: "100%",
          height: 6,
          appearance: "none",
          background: `linear-gradient(to right, var(--growth-galaxy) 0%, var(--growth-galaxy) ${pct}%, var(--gg-10) ${pct}%, var(--gg-10) 100%)`,
          borderRadius: 999,
          outline: "none",
          margin: 0
        }}
        className="money-slider" />
      
      <style>{`
        .money-slider::-webkit-slider-thumb {
          -webkit-appearance: none;
          width: 24px; height: 24px;
          border-radius: 50%;
          background: #fff;
          border: 3px solid var(--growth-galaxy);
          cursor: grab;
          box-shadow: 0 2px 8px rgba(0,64,186,0.30);
        }
        .money-slider::-moz-range-thumb {
          width: 24px; height: 24px;
          border-radius: 50%;
          background: #fff;
          border: 3px solid var(--growth-galaxy);
          cursor: grab;
          box-shadow: 0 2px 8px rgba(0,64,186,0.30);
        }
      `}</style>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontSize: 11, color: "var(--tt-60)" }}>
        <span>{fmt(min)}</span>
        <span>{fmt(max)}</span>
      </div>
    </div>);

};

// Export
Object.assign(window, {
  fmt, fmt2,
  Icon, Rings, Button, TextInput, SelectInput, Check, Steps,
  Disclosure, Eyebrow, Stat,
  RevenuedLogo, CapitalCobrand, PlaidCard, MoneySlider
});