/* Sentosa Marketplace - shared UI-kit primitives (Buyer + Seller portals)
   Implements the documented design system (design-system-prompt.md).
   Exports to window at the bottom for cross-file use. */

function Icon({ name, size = 20, strokeWidth = 2, color = "currentColor", style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const L = window.lucide;
    if (!L || !ref.current) return;
    const pascal = name.split("-").map(s => s[0].toUpperCase() + s.slice(1)).join("");
    const node = L.icons && L.icons[pascal];
    ref.current.innerHTML = "";
    if (node && L.createElement) {
      const svg = L.createElement(node);
      svg.setAttribute("width", size);
      svg.setAttribute("height", size);
      svg.setAttribute("stroke-width", strokeWidth);
      svg.style.color = color;
      svg.style.display = "block";
      ref.current.appendChild(svg);
    }
  });
  return <span ref={ref} aria-hidden="true" style={{ display: "inline-flex", flex: "none", ...style }}></span>;
}

/* ---- Button ---- */
function Btn({ variant = "primary", size = "md", icon, iconRight, children, onClick, type, full, disabled, ariaLabel }) {
  const base = {
    fontFamily: "var(--font-sans)", fontWeight: 600, cursor: disabled ? "not-allowed" : "pointer",
    borderRadius: "var(--radius-md)", border: "1.5px solid transparent", display: "inline-flex",
    alignItems: "center", justifyContent: "center", gap: 8, transition: "border-color .15s,box-shadow .15s",
    minHeight: size === "sm" ? 36 : 44, fontSize: size === "sm" ? 14 : 15,
    padding: size === "sm" ? "0 12px" : "0 18px", width: full ? "100%" : "auto", opacity: disabled ? 0.45 : 1,
  };
  const variants = {
    primary: { background: "var(--action)", color: "var(--fg-on-action)" },
    secondary: { background: "#fff", color: "var(--orange-900)", borderColor: "var(--orange-700)" },
    ghost: { background: "transparent", color: "var(--fg1)" },
    danger: { background: "var(--danger)", color: "#fff" },
    dark: { background: "#fff", color: "var(--black)", borderColor: "var(--neutral-300)" },
  };
  const hovers = {
    primary: "var(--action-hover)", secondary: "var(--orange-50)", ghost: "var(--neutral-100)", danger: "#b9241e", dark: "var(--neutral-50)",
  };
  const [h, setH] = React.useState(false);
  const st = { ...base, ...variants[variant] };
  if (h && !disabled) {
    if (variant === "primary" || variant === "danger") st.background = hovers[variant];
    else st.background = hovers[variant];
  }
  return (
    <button type={type || "button"} onClick={disabled ? undefined : onClick} disabled={disabled}
      aria-label={ariaLabel} style={st}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}>
      {icon && <Icon name={icon} size={size === "sm" ? 16 : 18} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "sm" ? 16 : 18} />}
    </button>
  );
}

/* ---- Badge ---- */
function Badge({ tone = "neutral", children, dot = true }) {
  const tones = {
    success: ["var(--success-bg)", "#0f5e35"], warning: ["var(--warning-bg)", "#7a5a00"],
    danger: ["var(--danger-bg)", "#8f1c17"], info: ["var(--info-bg)", "#1a44a8"],
    neutral: ["var(--neutral-100)", "var(--fg2)"], brand: ["var(--orange-50)", "#9A4F0C"],
  };
  const [bg, fg] = tones[tone];
  return (
    <span style={{ fontSize: 12, fontWeight: 600, padding: "4px 11px", borderRadius: "var(--radius-pill)",
      display: "inline-flex", alignItems: "center", gap: 5, background: bg, color: fg, lineHeight: 1.4, whiteSpace: "nowrap" }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: 999, background: "currentColor", flex: "none" }}></span>}
      {children}
    </span>
  );
}

/* ---- Form field ---- */
function Field({ label, required, optional, error, help, value, onChange, placeholder, type = "text", prefix, as, children }) {
  const [f, setF] = React.useState(false);
  const border = error ? "var(--danger)" : f ? "var(--orange-700)" : "var(--border)";
  const shared = {
    fontFamily: "var(--font-sans)", fontSize: 15, width: "100%", boxSizing: "border-box", minHeight: 44,
    padding: prefix ? "0 12px 0 32px" : "0 12px", borderRadius: "var(--radius-md)",
    border: `1.5px solid ${border}`, background: "#fff", color: "var(--fg1)", outline: "none",
    boxShadow: f ? "var(--focus-ring)" : "none",
  };
  return (
    <div style={{ width: "100%" }}>
      {label && <label style={{ display: "block", fontSize: 13, fontWeight: 600, marginBottom: 6 }}>
        {label}{required && <span style={{ color: "var(--fg3)", fontWeight: 400 }}> (required)</span>}
        {optional && <span style={{ color: "var(--fg3)", fontWeight: 400 }}> (optional)</span>}
      </label>}
      <div style={{ position: "relative" }}>
        {prefix && <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg3)" }}>{prefix}</span>}
        {as === "select"
          ? <select value={value} onChange={onChange} onFocus={() => setF(true)} onBlur={() => setF(false)} style={{ ...shared, appearance: "none" }}>{children}</select>
          : as === "textarea"
          ? <textarea value={value} onChange={onChange} placeholder={placeholder} onFocus={() => setF(true)} onBlur={() => setF(false)} rows={3} style={{ ...shared, minHeight: 80, padding: 12, resize: "vertical", lineHeight: 1.5 }} />
          : <input type={type} value={value} onChange={onChange} placeholder={placeholder} onFocus={() => setF(true)} onBlur={() => setF(false)} style={shared} />}
      </div>
      {error
        ? <div style={{ fontSize: 12, color: "var(--danger)", marginTop: 5, display: "flex", alignItems: "center", gap: 5, fontWeight: 500 }}><Icon name="alert-circle" size={14} />{error}</div>
        : help && <div style={{ fontSize: 12, color: "var(--fg2)", marginTop: 5 }}>{help}</div>}
    </div>
  );
}

/* ---- Government trust band (thin strip above the app bar) ---- */
function GovBand() {
  const { t } = useLang();
  return (
    <div style={{ background: "var(--true-black)", color: "#C9C9C9", fontSize: 12.5, padding: "6px 0" }}>
      <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "0 24px", display: "flex", alignItems: "center", gap: 8 }}>
        <Icon name="landmark" size={14} color="#9A9A9A" />
        <span>{t("gov_band")}</span>
        <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}><Icon name="lock" size={13} color="#9A9A9A" />{t("secure")}</span>
      </div>
    </div>
  );
}

/* ---- Logo wordmark ---- */
function Logo({ height = 26, href }) {
  const img = <img src="../../assets/sentosa-logo.png" alt="Sentosa"
    style={{ height, width: "auto", flexShrink: 0, display: "block" }} />;
  if (href === null) return img;
  return (
    <a href={href || "../../index.html"} title="Back to Sentosa B2B Marketplace home"
       style={{ display: "inline-flex", alignItems: "center", flexShrink: 0, borderRadius: 4, textDecoration: "none" }}>
      {img}
    </a>
  );
}

/* ---- Card shell ---- */
function Card({ children, pad = 16, style, hover, onClick }) {
  const [h, setH] = React.useState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)",
        padding: pad, boxShadow: hover && h ? "var(--elev-1)" : "none", transition: "box-shadow .15s, transform .15s",
        cursor: onClick ? "pointer" : "default", ...style }}>
      {children}
    </div>
  );
}

/* ---- Singapore Government masthead (mandatory on every .gov.sg page) ---- */
function SgGovMasthead() {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ background: "#F0F0F0", color: "#5B5B5B", fontSize: 14, fontFamily: "var(--font-sans)" }}>
      <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "5px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {/* simplified SG flag */}
          <span aria-hidden="true" style={{ width: 18, height: 12, borderRadius: 2, overflow: "hidden", display: "inline-flex", flexDirection: "column", flex: "none", boxShadow: "0 0 0 1px rgba(0,0,0,.08)" }}>
            <span style={{ flex: 1, background: "#EF3340" }}></span><span style={{ flex: 1, background: "#fff" }}></span>
          </span>
          <span>A Singapore Government Agency Website</span>
          <button onClick={() => setOpen(o => !o)} aria-expanded={open}
            style={{ background: "none", border: 0, cursor: "pointer", color: "#5B5B5B", fontFamily: "var(--font-sans)", fontSize: 14, display: "inline-flex", alignItems: "center", gap: 3, padding: 0, textDecoration: "underline", textUnderlineOffset: 2 }}>
            How to identify <Icon name={open ? "chevron-up" : "chevron-down"} size={15} />
          </button>
        </div>
        {open && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, padding: "16px 0 18px", maxWidth: 820 }}>
            {[["landmark", "Official website links end with .gov.sg", "Government agencies communicate via .gov.sg websites (e.g. go.gov.sg/open)."],
              ["lock", "Secure websites use HTTPS", "Look for a lock or https:// as an added precaution. Share sensitive information only on official, secure websites."]].map(([ic, h, b]) => (
              <div key={h} style={{ display: "flex", gap: 10 }}>
                <Icon name={ic} size={18} color="#5B5B5B" style={{ marginTop: 2 }} />
                <div style={{ lineHeight: 1.5 }}><div style={{ fontWeight: 600, color: "#323232" }}>{h}</div><div style={{ fontSize: 13.5 }}>{b}</div></div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

/* ---- Scam advisory strip (as shown on sentosa.gov.sg) ---- */
function ScamAdvisory() {
  return (
    <div style={{ background: "#FCF3DA", borderBottom: "1px solid #F0DCA0", color: "#7A5A00", fontSize: 13.5, lineHeight: 1.5 }}>
      <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "9px 24px", display: "flex", gap: 9, alignItems: "flex-start" }}>
        <Icon name="shield-alert" size={17} style={{ marginTop: 1, flex: "none" }} />
        <span>Government officials will <strong>never</strong> ask you to transfer money or disclose bank log-in details over a phone call. If in doubt, call the 24/7 ScamShield hotline at <strong>1799</strong>.</span>
      </div>
    </div>
  );
}

Object.assign(window, { Icon, Btn, Badge, Field, GovBand, Logo, Card, SgGovMasthead, ScamAdvisory });
