/* Shared UI primitives used across the three SPIF tracker variations.
 *
 * Everything sits inside an `pb-surface-private` body, so headlines use
 * Avenir Next via --font-sans-private. Tables and tabular numbers use
 * font-feature-settings: 'tnum' for alignment.
 */

const { useState, useMemo, useEffect } = React;

/* ---------- App shell ---------- */

function AppHeader({ subtitle, right, homeHref }) {
  const brand = (
    <div style={{ display: "flex", alignItems: "center", gap: 14, textDecoration: "none" }}>
        <img src="system/logos/pb-logo-light.svg" alt="PartsBase" style={{ height: 26, width: "auto", display: "block" }} />
        <div style={{ width: 1, height: 28, background: "var(--gray-200)" }}></div>
        <div>
          <div style={{
            fontSize: 17, fontWeight: 700, color: "var(--color-800)",
            fontFamily: "var(--font-sans-private)", letterSpacing: "-0.01em",
            lineHeight: 1.2,
          }}>
            SPIF Tracker
          </div>
          {subtitle && (
            <div style={{
              fontSize: 12, color: "var(--gray-500)", marginTop: 1,
              fontFamily: "var(--font-sans-private)",
            }}>{subtitle}</div>
          )}
        </div>
    </div>
  );
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "20px 32px", background: "#fff",
      borderBottom: "1px solid var(--gray-200)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
        {homeHref && (
          <a href={homeHref} title="All SPIFs" style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            color: "var(--gray-500)", textDecoration: "none",
            fontSize: 13, fontWeight: 500, fontFamily: "var(--font-sans-private)",
            paddingRight: 18, borderRight: "1px solid var(--gray-200)",
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
            All SPIFs
          </a>
        )}
        {homeHref ? <a href={homeHref} style={{ textDecoration: "none" }}>{brand}</a> : brand}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        {right}
        <div style={{
          fontSize: 12, color: "var(--gray-500)",
          fontFamily: "var(--font-sans-private)",
        }}>
          As of {fmtDate(TODAY)}
        </div>
        {(typeof window !== "undefined" && window.AuthMenu)
          ? React.createElement(window.AuthMenu)
          : (
            <div style={{
              width: 32, height: 32, borderRadius: 999,
              background: "var(--color-100)", color: "var(--color-700)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 12, fontWeight: 600,
              fontFamily: "var(--font-sans-private)",
            }}>SO</div>
          )}
      </div>
    </div>
  );
}

/* ---------- KPI / stat ---------- */

function StatTile({ label, value, sub, accent }) {
  return (
    <div style={{
      padding: "16px 20px",
      background: "#fff",
      border: "1px solid var(--gray-200)",
      borderRadius: 12,
      minWidth: 0,
    }}>
      <div style={{
        fontSize: 11, fontWeight: 600, letterSpacing: "0.08em",
        textTransform: "uppercase", color: "var(--gray-500)",
        marginBottom: 8,
        fontFamily: "var(--font-sans-private)",
      }}>{label}</div>
      <div style={{
        fontSize: 28, fontWeight: 700, color: accent || "var(--color-800)",
        letterSpacing: "-0.02em", lineHeight: 1,
        fontFamily: "var(--font-sans-private)",
        fontFeatureSettings: "'tnum'",
      }}>{value}</div>
      {sub && (
        <div style={{
          fontSize: 12, color: "var(--gray-500)", marginTop: 6,
          fontFamily: "var(--font-sans-private)",
        }}>{sub}</div>
      )}
    </div>
  );
}

/* ---------- Status pill ---------- */

function StatusPill({ status, size = "sm" }) {
  const map = {
    qualified: { label: "Qualified",  cls: "pb-badge-success" },
    pending:   { label: "Pending",    cls: "pb-badge-info" },
    expired:   { label: "Expired",    cls: "pb-badge-error" },
    paid:      { label: "Paid",       cls: "pb-badge-success" },
    active:    { label: "Active",     cls: "pb-badge-success" },
    inactive:  { label: "Inactive",   cls: "pb-badge-default" },
  };
  const s = map[status] || { label: status, cls: "pb-badge-default" };
  return (
    <span className={`pb-badge pb-badge-${size} ${s.cls}`}
      style={{ padding: "1px 10px", minHeight: 18, fontSize: 11, lineHeight: 1.5 }}>
      <svg width="6" height="6" viewBox="0 0 6 6"><circle cx="3" cy="3" r="3" /></svg>
      {s.label}
    </span>
  );
}

/* ---------- Countdown bar ---------- */
/* Visual: a horizontal track with elapsed fill + a "deadline" marker.
 * Color encodes urgency: green if qualified, blue if plenty of runway,
 * amber under 30 days, red expired. */

function CountdownBar({ hire, height = 6, showLabels = false }) {
  const { status, elapsed, remaining, totalDays, percent } = hire;
  let fill = "var(--color-500)";
  if (status === "qualified") fill = "var(--success-500)";
  else if (status === "expired") fill = "var(--error-500)";
  else if (remaining <= 30) fill = "var(--warning-500)";

  return (
    <div style={{ width: "100%" }}>
      <div style={{
        position: "relative",
        height,
        background: "var(--gray-200)",
        borderRadius: height,
        overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", inset: 0,
          width: `${percent}%`,
          background: fill,
          borderTopRightRadius: height, borderBottomRightRadius: height,
          transition: "width 0.3s ease",
        }} />
      </div>
      {showLabels && (
        <div style={{
          display: "flex", justifyContent: "space-between",
          marginTop: 4, fontSize: 11, color: "var(--gray-500)",
          fontFamily: "var(--font-sans-private)",
          fontFeatureSettings: "'tnum'",
        }}>
          <span>Day {elapsed} of {totalDays}</span>
          <span>{status === "qualified" ? "✓ closed in window"
                : status === "expired" ? "window closed"
                : `${remaining} days left`}</span>
        </div>
      )}
    </div>
  );
}

/* ---------- Section heading ---------- */

function SectionHeading({ icon, title, subtitle, right, badge }) {
  return (
    <div style={{
      display: "flex", alignItems: "flex-start", justifyContent: "space-between",
      gap: 16, marginBottom: 16,
    }}>
      <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
        {icon && (
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: "var(--color-100)", color: "var(--color-700)",
            display: "flex", alignItems: "center", justifyContent: "center",
            flexShrink: 0,
          }}>{icon}</div>
        )}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h2 style={{
              margin: 0, fontSize: 20, fontWeight: 700,
              color: "var(--color-800)",
              fontFamily: "var(--font-sans-private)",
              letterSpacing: "-0.01em",
            }}>{title}</h2>
            {badge}
          </div>
          {subtitle && (
            <div style={{
              fontSize: 13, color: "var(--gray-600)", marginTop: 4,
              fontFamily: "var(--font-sans-private)",
              maxWidth: 720,
            }}>{subtitle}</div>
          )}
        </div>
      </div>
      <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
        {right}
      </div>
    </div>
  );
}

/* ---------- Table primitives ---------- */

const TABLE_FONT = {
  fontFamily: "var(--font-sans-private)",
  fontSize: 13,
  color: "var(--gray-800)",
};

function Th({ children, align = "left", width }) {
  return (
    <th style={{
      ...TABLE_FONT,
      fontWeight: 600,
      fontSize: 11,
      letterSpacing: "0.06em",
      textTransform: "uppercase",
      color: "var(--gray-500)",
      textAlign: align,
      padding: "10px 12px",
      borderBottom: "1px solid var(--gray-200)",
      background: "var(--gray-50)",
      width,
    }}>{children}</th>
  );
}

function Td({ children, align = "left", mono = false, color, weight, width, style, density }) {
  const padding = density === "compact" ? "7px 12px"
                : density === "comfy"   ? "16px 12px"
                : "12px 12px";
  return (
    <td style={{
      ...TABLE_FONT,
      padding,
      borderBottom: "1px solid var(--gray-200)",
      textAlign: align,
      fontFeatureSettings: mono ? "'tnum'" : undefined,
      color: color || "var(--gray-800)",
      fontWeight: weight,
      width,
      verticalAlign: "middle",
      ...style,
    }}>{children}</td>
  );
}

/* ---------- Icons (inline Feather-style) ---------- */

function Icon({ name, size = 16, color = "currentColor" }) {
  const common = {
    width: size, height: size, viewBox: "0 0 24 24",
    fill: "none", stroke: color, strokeWidth: 2,
    strokeLinecap: "round", strokeLinejoin: "round",
  };
  const paths = {
    users: <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
    "user-plus": <><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></>,
    award: <><circle cx="12" cy="8" r="7"/><polyline points="8.21 13.89 7 23 12 20 17 23 15.79 13.88"/></>,
    "trending-up": <><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></>,
    clock: <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></>,
    plus: <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    minus: <line x1="5" y1="12" x2="19" y2="12"/>,
    trash: <><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></>,
    monitor: <><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></>,
    edit: <><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></>,
    chevron: <polyline points="9 18 15 12 9 6"/>,
    "chevron-down": <polyline points="6 9 12 15 18 9"/>,
    search: <><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></>,
    filter: <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>,
    download: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    briefcase: <><rect x="2" y="7" width="20" height="14" rx="2" ry="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></>,
    "dollar-sign": <><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></>,
    check: <polyline points="20 6 9 17 4 12"/>,
    info: <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    "more-h": <><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></>,
    calendar: <><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></>,
  };
  return <svg {...common}>{paths[name]}</svg>;
}

/* ---------- Avatar ---------- */

function Avatar({ name, size = 28, tone = "blue" }) {
  const initials = name.split(" ").map(w => w[0]).slice(0, 2).join("");
  const tones = {
    blue:    { bg: "var(--color-100)",   fg: "var(--color-700)" },
    indigo:  { bg: "#E0E7FF",            fg: "#3730A3" },
    teal:    { bg: "#CCFBF1",            fg: "#0F766E" },
    amber:   { bg: "var(--warning-100)", fg: "var(--warning-700)" },
    rose:    { bg: "#FFE4E6",            fg: "#9F1239" },
    violet:  { bg: "#EDE9FE",            fg: "#5B21B6" },
    gray:    { bg: "var(--gray-100)",    fg: "var(--gray-700)" },
  };
  const t = tones[tone] || tones.blue;
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      background: t.bg, color: t.fg,
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontSize: size <= 24 ? 10 : 11, fontWeight: 600,
      fontFamily: "var(--font-sans-private)",
      letterSpacing: "0.02em", flexShrink: 0,
    }}>{initials}</div>
  );
}

/* Pick a tone deterministically from a name */
function toneFor(name) {
  const tones = ["blue","indigo","teal","amber","rose","violet"];
  let h = 0;
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
  return tones[h % tones.length];
}

/* Live sync indicator — reads syncStatus from the store. */
function SyncBadge() {
  const ctx = (typeof useStore === "function") ? useStore() : null;
  const status = ctx ? ctx.syncStatus : "local";
  const map = {
    synced:     { dot: "var(--success-500)", label: "Live · synced",   color: "var(--success-700)", bg: "var(--success-50)" },
    connecting: { dot: "var(--warning-500)", label: "Connecting…",      color: "var(--warning-700)", bg: "var(--warning-50)" },
    local:      { dot: "var(--gray-400)",    label: "Local only",       color: "var(--gray-600)",    bg: "var(--gray-100)" },
  };
  const s = map[status] || map.local;
  return (
    <span title={status === "synced" ? "Changes sync live for everyone" : status === "connecting" ? "Reconnecting to shared data" : "Not connected — changes stay on this device"}
      style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        fontSize: 11, fontWeight: 600, color: s.color, background: s.bg,
        padding: "4px 10px", borderRadius: 999,
        fontFamily: "var(--font-sans-private)",
      }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: s.dot,
        boxShadow: status === "synced" ? "0 0 0 3px color-mix(in srgb, var(--success-500) 18%, transparent)" : "none" }} />
      {s.label}
    </span>
  );
}

Object.assign(window, {
  AppHeader, StatTile, StatusPill, CountdownBar, SectionHeading,
  Th, Td, Icon, Avatar, toneFor, SyncBadge,
});
