// ---------- Shared primitives ----------

// HarborDock wordmark + monogram (using real assets)
const HDMark = ({ size = 28, light = false, plain = false }) => {
  // The real PNG mark — black on transparent. Invert filter for dark contexts.
  const img = (
    <img
      src="assets/harbordock-mark.png"
      alt="HarborDock"
      style={{
        width: "76%", height: "76%", objectFit: "contain",
        filter: light ? "none" : "invert(1)",
        opacity: light ? 0.92 : 1,
      }}
    />
  );
  if (plain) {
    return (
      <div style={{
        width: size, height: size,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
      }}>{img}</div>
    );
  }
  return (
    <div style={{
      width: size, height: size, borderRadius: Math.max(4, size * 0.18),
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      background: light ? "var(--paper)" : "var(--charcoal)",
      border: light ? "1px solid rgba(8,12,16,0.08)" : "1px solid rgba(255,255,255,0.06)",
      flexShrink: 0,
    }}>
      {img}
    </div>
  );
};

const HDWordmark = ({ light = false, size = "md", sub = false }) => {
  const fg = light ? "var(--ink)" : "var(--white)";
  const muted = light ? "rgba(8,12,16,0.55)" : "rgba(250,250,250,0.55)";
  const fontSize = size === "lg" ? 22 : size === "sm" ? 14 : 17;
  return (
    <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
      <span
        style={{
          fontFamily: "var(--serif)",
          fontSize,
          letterSpacing: size === "lg" ? "0.18em" : "0.16em",
          color: fg,
          textTransform: "uppercase",
          fontWeight: 500,
        }}
      >
        HARBORDOCK
      </span>
      {sub && (
        <span
          className="micro"
          style={{ color: muted, marginTop: 6, letterSpacing: "0.24em", fontSize: 9 }}
        >
          CLIENT PORTALS FOR CREATIVE TEAMS
        </span>
      )}
    </div>
  );
};

// Combined mark + wordmark — horizontal lockup for nav bars
const HDLockup = ({ light = false, markSize = 32 }) => (
  <div style={{ display: "inline-flex", alignItems: "center", gap: 12 }}>
    <HDMark size={markSize} light={light} />
    <HDWordmark light={light} size="md" />
  </div>
);

// Status badge — pill with dot
const STATUS_TONES = {
  harbor:   { fg: "#9CC1FF", bg: "rgba(29,78,216,0.14)",  bd: "rgba(29,78,216,0.34)",  dot: "#3B82F6" },
  teal:     { fg: "#7CE3D2", bg: "rgba(20,184,166,0.12)", bd: "rgba(20,184,166,0.32)", dot: "#14B8A6" },
  amber:    { fg: "#FBD487", bg: "rgba(245,158,11,0.12)", bd: "rgba(245,158,11,0.32)", dot: "#F59E0B" },
  lavender: { fg: "#C4A8FF", bg: "rgba(139,92,246,0.14)", bd: "rgba(139,92,246,0.32)", dot: "#8B5CF6" },
  steel:    { fg: "#CBD5E1", bg: "rgba(148,163,184,0.10)",bd: "rgba(148,163,184,0.24)",dot: "#94A3B8" },
  green:    { fg: "#86EFAC", bg: "rgba(34,197,94,0.12)",  bd: "rgba(34,197,94,0.30)",  dot: "#22C55E" },
  neutral:  { fg: "#D4D4D4", bg: "rgba(255,255,255,0.05)",bd: "rgba(255,255,255,0.10)",dot: "#A3A3A3" },
};

const STATUS_MAP = {
  review:     { tone: "harbor",   label: "In review" },
  revision:   { tone: "amber",    label: "Revision" },
  uploading:  { tone: "teal",     label: "Client upload" },
  approved:   { tone: "green",    label: "Approved" },
  delivered:  { tone: "steel",    label: "Delivered" },
  drafting:   { tone: "lavender", label: "Drafting" },
  open:       { tone: "amber",    label: "Open" },
  resolved:   { tone: "green",    label: "Resolved" },
  awaiting:   { tone: "amber",    label: "Awaiting approval" },
  ready:      { tone: "harbor",   label: "Ready" },
  "not-started":{ tone: "neutral", label: "Not started" },
  done:       { tone: "green",    label: "Done" },
  "in-progress":{ tone: "harbor", label: "In progress" },
  queued:     { tone: "neutral",  label: "Queued" },
  active:     { tone: "harbor",   label: "Active" },
  complete:   { tone: "green",    label: "Complete" },
  retainer:   { tone: "lavender", label: "Retainer" },
  paused:     { tone: "neutral",  label: "Paused" },
};

const StatusBadge = ({ status, label, tone: explicitTone, size = "md", solid = false }) => {
  const meta = STATUS_MAP[status] || { tone: explicitTone || "neutral", label: label || status };
  const tone = STATUS_TONES[explicitTone || meta.tone];
  const text = label || meta.label;
  const pad = size === "sm" ? "3px 8px" : "4px 10px";
  const fz = size === "sm" ? 10.5 : 11.5;
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: pad,
        background: solid ? tone.dot : tone.bg,
        border: `1px solid ${solid ? tone.dot : tone.bd}`,
        color: solid ? "white" : tone.fg,
        borderRadius: 99,
        fontSize: fz,
        fontWeight: 500,
        letterSpacing: "0.02em",
        whiteSpace: "nowrap",
      }}
    >
      <span style={{
        width: 6, height: 6, borderRadius: 99,
        background: solid ? "rgba(255,255,255,0.85)" : tone.dot,
        boxShadow: solid ? "none" : `0 0 0 2px ${tone.bg}`,
      }} />
      {text}
    </span>
  );
};

// Avatar — initials chip
const Avatar = ({ initials, accent = "neutral", size = 28, ring = false }) => {
  const t = STATUS_TONES[accent] || STATUS_TONES.neutral;
  return (
    <div
      style={{
        width: size, height: size, borderRadius: 99,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        background: `linear-gradient(135deg, ${t.bg}, rgba(255,255,255,0.02))`,
        border: `1px solid ${t.bd}`,
        color: t.fg,
        fontSize: size > 32 ? 12 : 10.5,
        fontWeight: 600,
        letterSpacing: "0.04em",
        flexShrink: 0,
        boxShadow: ring ? `0 0 0 2px var(--ink), 0 0 0 3px ${t.bd}` : "none",
      }}
    >
      {initials}
    </div>
  );
};

// Avatar stack
const AvatarStack = ({ people, max = 3, size = 22 }) => (
  <div style={{ display: "inline-flex", alignItems: "center" }}>
    {people.slice(0, max).map((p, i) => (
      <div key={i} style={{ marginLeft: i === 0 ? 0 : -8 }}>
        <Avatar initials={p.initials} accent={p.accent} size={size} ring />
      </div>
    ))}
    {people.length > max && (
      <div
        style={{
          marginLeft: -8,
          width: size, height: size, borderRadius: 99,
          background: "var(--slate)", border: "1px solid rgba(255,255,255,0.10)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          fontSize: 10, color: "var(--white)", boxShadow: "0 0 0 2px var(--ink)",
        }}
      >
        +{people.length - max}
      </div>
    )}
  </div>
);

// Progress bar
const Progress = ({ value, tone = "harbor", track = "rgba(255,255,255,0.06)", height = 4 }) => {
  const t = STATUS_TONES[tone];
  return (
    <div style={{ height, background: track, borderRadius: 99, overflow: "hidden" }}>
      <div
        style={{
          width: `${value}%`,
          height: "100%",
          background: `linear-gradient(90deg, ${t.dot}, ${t.fg})`,
          borderRadius: 99,
          transition: "width 600ms cubic-bezier(.16,1,.3,1)",
        }}
      />
    </div>
  );
};

// Button
const Button = ({ children, variant = "primary", size = "md", onClick, icon, iconRight, light = false, full = false, style = {}, type = "button" }) => {
  const sizes = {
    sm: { p: "6px 10px", fz: 12, h: 28 },
    md: { p: "8px 14px", fz: 13, h: 36 },
    lg: { p: "12px 22px", fz: 14, h: 48 },
  }[size];
  const variants = {
    primary: {
      background: "var(--harbor)",
      color: "white",
      border: "1px solid var(--harbor)",
      boxShadow: "0 1px 0 rgba(255,255,255,0.10) inset, 0 6px 16px -8px rgba(29,78,216,0.55)",
    },
    secondary: light ? {
      background: "var(--ink)",
      color: "var(--white)",
      border: "1px solid var(--ink)",
    } : {
      background: "var(--white)",
      color: "var(--ink)",
      border: "1px solid var(--white)",
    },
    ghost: light ? {
      background: "transparent",
      color: "var(--ink)",
      border: "1px solid rgba(8,12,16,0.14)",
    } : {
      background: "transparent",
      color: "var(--white)",
      border: "1px solid rgba(255,255,255,0.12)",
    },
    subtle: light ? {
      background: "rgba(8,12,16,0.04)",
      color: "var(--ink)",
      border: "1px solid transparent",
    } : {
      background: "rgba(255,255,255,0.04)",
      color: "var(--white)",
      border: "1px solid rgba(255,255,255,0.06)",
    },
  }[variant];
  return (
    <button
      type={type}
      onClick={onClick}
      style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
        height: sizes.h, padding: sizes.p, borderRadius: 8,
        fontSize: sizes.fz, fontWeight: 500, fontFamily: "var(--sans)",
        boxSizing: "border-box",
        cursor: "pointer", transition: "transform 120ms ease, background 120ms ease, border-color 120ms ease",
        width: full ? "100%" : "auto",
        whiteSpace: "nowrap",
        ...variants,
        ...style,
      }}
      onMouseEnter={(e) => (e.currentTarget.style.transform = "translateY(-1px)")}
      onMouseLeave={(e) => (e.currentTarget.style.transform = "translateY(0)")}
    >
      {icon}
      {children}
      {iconRight}
    </button>
  );
};

// Card (dark surface)
const Card = ({ children, style = {}, hover = false, onClick, light = false, className = "" }) => (
  <div
    className={className}
    onClick={onClick}
    style={{
      background: light ? "var(--white)" : "var(--charcoal)",
      border: light ? "1px solid rgba(8,12,16,0.06)" : "1px solid rgba(255,255,255,0.06)",
      borderRadius: 14,
      transition: "transform 200ms ease, border-color 200ms ease, box-shadow 200ms ease",
      cursor: onClick ? "pointer" : "default",
      ...style,
    }}
    onMouseEnter={hover ? (e) => {
      e.currentTarget.style.borderColor = light ? "rgba(8,12,16,0.16)" : "rgba(255,255,255,0.14)";
      e.currentTarget.style.transform = "translateY(-2px)";
    } : undefined}
    onMouseLeave={hover ? (e) => {
      e.currentTarget.style.borderColor = light ? "rgba(8,12,16,0.06)" : "rgba(255,255,255,0.06)";
      e.currentTarget.style.transform = "translateY(0)";
    } : undefined}
  >
    {children}
  </div>
);

// Section header
const SectionHeader = ({ eyebrow, title, action, dense = false }) => (
  <div style={{
    display: "flex", alignItems: "flex-end", justifyContent: "space-between",
    marginBottom: dense ? 12 : 16, gap: 12,
  }}>
    <div>
      {eyebrow && <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 6 }}>{eyebrow}</div>}
      <h2 style={{
        margin: 0,
        fontFamily: "var(--sans)",
        fontSize: dense ? 14 : 16,
        fontWeight: 600,
        color: "var(--white)",
        letterSpacing: "-0.005em",
      }}>{title}</h2>
    </div>
    {action}
  </div>
);

// Stat card
const StatCard = ({ label, value, detail, tone = "harbor", iconName }) => {
  const t = STATUS_TONES[tone];
  const IconComp = window.Icon[iconName] || window.Icon.Folder;
  return (
    <div style={{
      background: "var(--charcoal)",
      border: "1px solid rgba(255,255,255,0.06)",
      borderRadius: 14,
      padding: 18,
      position: "relative",
      overflow: "hidden",
    }}>
      <div style={{
        position: "absolute", inset: 0,
        background: `radial-gradient(circle at 100% 0%, ${t.bg}, transparent 60%)`,
        pointerEvents: "none",
      }} />
      <div style={{ position: "relative", display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <div className="micro" style={{ color: "var(--warm-gray)" }}>{label}</div>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: t.bg, border: `1px solid ${t.bd}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.fg,
        }}><IconComp size={14} /></div>
      </div>
      <div style={{
        position: "relative",
        fontFamily: "var(--serif)", fontWeight: 500,
        fontSize: 40, lineHeight: 1, marginTop: 14, letterSpacing: "-0.02em",
        color: "var(--white)",
      }}>{value}</div>
      <div style={{ position: "relative", marginTop: 8, fontSize: 12, color: "var(--warm-gray)" }}>{detail}</div>
    </div>
  );
};

// Empty State
const EmptyState = ({ iconName = "Folder", title, body, action }) => {
  const IconComp = window.Icon[iconName];
  return (
    <div style={{
      padding: "48px 24px", textAlign: "center",
      border: "1px dashed rgba(255,255,255,0.10)", borderRadius: 14,
      background: "rgba(255,255,255,0.01)",
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 12, margin: "0 auto 16px",
        background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)",
        display: "flex", alignItems: "center", justifyContent: "center", color: "var(--warm-gray)",
      }}><IconComp size={20} /></div>
      <div style={{ fontSize: 14, fontWeight: 500, color: "var(--white)" }}>{title}</div>
      <div style={{ fontSize: 13, color: "var(--warm-gray)", marginTop: 6, maxWidth: 320, marginLeft: "auto", marginRight: "auto" }}>{body}</div>
      {action && <div style={{ marginTop: 18 }}>{action}</div>}
    </div>
  );
};

// Skeleton
const Skeleton = ({ w = "100%", h = 12, r = 6, style = {} }) => (
  <div style={{
    width: w, height: h, borderRadius: r,
    background: "linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.04) 100%)",
    backgroundSize: "200% 100%",
    animation: "hd-shimmer 1.4s linear infinite",
    ...style,
  }} />
);

// IconButton
const IconButton = ({ iconName, onClick, light = false, label, active = false }) => {
  const IconComp = window.Icon[iconName];
  return (
    <button
      onClick={onClick}
      aria-label={label}
      style={{
        width: 32, height: 32, borderRadius: 8,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        background: active
          ? (light ? "rgba(8,12,16,0.06)" : "rgba(255,255,255,0.06)")
          : "transparent",
        border: light
          ? "1px solid rgba(8,12,16,0.10)"
          : "1px solid rgba(255,255,255,0.08)",
        color: light ? "var(--ink)" : "var(--white)",
        cursor: "pointer", transition: "background 120ms ease",
      }}
      onMouseEnter={(e) => (e.currentTarget.style.background = light ? "rgba(8,12,16,0.04)" : "rgba(255,255,255,0.04)")}
      onMouseLeave={(e) => (e.currentTarget.style.background = active ? (light ? "rgba(8,12,16,0.06)" : "rgba(255,255,255,0.06)") : "transparent")}
    >
      <IconComp size={15} />
    </button>
  );
};

// Inline keyboard chip
const Kbd = ({ children, light = false }) => (
  <span
    className="mono"
    style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      minWidth: 18, height: 18, padding: "0 5px", borderRadius: 4,
      background: light ? "rgba(8,12,16,0.05)" : "rgba(255,255,255,0.06)",
      border: light ? "1px solid rgba(8,12,16,0.10)" : "1px solid rgba(255,255,255,0.08)",
      color: light ? "var(--ink)" : "var(--white)",
      fontSize: 10, fontWeight: 500, letterSpacing: 0,
    }}
  >{children}</span>
);

// Subtle divider
const Divider = ({ light = false, style = {} }) => (
  <div style={{
    height: 1,
    background: light ? "rgba(8,12,16,0.08)" : "rgba(255,255,255,0.06)",
    ...style,
  }} />
);

// Asset thumb (placeholder)
const AssetThumb = ({ type = "video", duration, tone = "stone" }) => {
  const IconComp = type === "video" ? window.Icon.Film
    : type === "image" ? window.Icon.Image
    : type === "audio" ? window.Icon.Mic
    : window.Icon.File;
  const bg = tone === "harbor"
    ? "linear-gradient(135deg, #16171A 0%, #1D4ED8 200%)"
    : "linear-gradient(135deg, #16171A, #2E3136)";
  return (
    <div style={{
      width: "100%", aspectRatio: "16/9",
      borderRadius: 8, overflow: "hidden", position: "relative",
      background: bg,
      border: "1px solid rgba(255,255,255,0.08)",
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      {/* subtle topographic lines */}
      <svg width="100%" height="100%" viewBox="0 0 160 90" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, opacity: 0.18 }}>
        {[10, 22, 36, 52, 70, 88].map((y, i) => (
          <path key={i} d={`M 0 ${y} Q 40 ${y - 8} 80 ${y} T 160 ${y}`} stroke="white" fill="none" strokeWidth="0.5" />
        ))}
      </svg>
      <div style={{
        width: 44, height: 44, borderRadius: 99,
        background: "rgba(0,0,0,0.4)", border: "1px solid rgba(255,255,255,0.18)",
        backdropFilter: "blur(8px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: "var(--white)",
      }}><IconComp size={18} /></div>
      {duration && (
        <span className="mono" style={{
          position: "absolute", bottom: 8, right: 8,
          background: "rgba(0,0,0,0.5)", border: "1px solid rgba(255,255,255,0.12)",
          padding: "2px 6px", borderRadius: 4,
          fontSize: 10, color: "var(--white)",
        }}>{duration}</span>
      )}
    </div>
  );
};

// Animations and shared keyframes
const sharedStyleEl = document.createElement("style");
sharedStyleEl.textContent = `
@keyframes hd-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
@keyframes hd-fadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
@keyframes hd-fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes hd-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
@keyframes hd-pulseRing { 0% { box-shadow: 0 0 0 0 rgba(29,78,216,0.4); } 70% { box-shadow: 0 0 0 8px rgba(29,78,216,0); } 100% { box-shadow: 0 0 0 0 rgba(29,78,216,0); } }
@keyframes hd-marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
.hd-fadeUp { animation: hd-fadeUp 540ms cubic-bezier(.16,1,.3,1) both; }
.hd-fadeIn { animation: hd-fadeIn 540ms cubic-bezier(.16,1,.3,1) both; }
.hd-pulse { animation: hd-pulse 1.8s ease-in-out infinite; }
.hd-pulseRing { animation: hd-pulseRing 2.4s ease-out infinite; }
.hd-reveal { opacity: 0; transform: translateY(16px); transition: opacity 800ms cubic-bezier(.16,1,.3,1), transform 800ms cubic-bezier(.16,1,.3,1); }
.hd-reveal.in { opacity: 1; transform: translateY(0); }
.hd-nav-item:hover { background: rgba(255,255,255,0.04) !important; color: var(--white) !important; }
.hd-row:hover { background: rgba(255,255,255,0.025) !important; }
.hd-row-light:hover { background: rgba(8,12,16,0.025) !important; }
.hd-mobile-only { display: none; }
.hd-sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 39; backdrop-filter: blur(2px); }
.hd-marquee-track { display: flex; gap: 64px; animation: hd-marquee 32s linear infinite; width: fit-content; }
* { scroll-behavior: smooth; }
`;
document.head.appendChild(sharedStyleEl);

// Reveal hook — fades in when scrolled into view
const useReveal = () => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach(e => {
          if (e.isIntersecting) {
            el.classList.add("in");
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.12 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
};

const Reveal = ({ children, delay = 0, as: As = "div", style = {}, ...rest }) => {
  const ref = useReveal();
  return (
    <As ref={ref} className="hd-reveal" style={{ transitionDelay: `${delay}ms`, ...style }} {...rest}>
      {children}
    </As>
  );
};

Object.assign(window, {
  HDMark, HDWordmark, HDLockup, StatusBadge, Avatar, AvatarStack, Progress, Button, Card,
  SectionHeader, StatCard, EmptyState, Skeleton, IconButton, Kbd, Divider,
  AssetThumb, STATUS_TONES, Reveal, useReveal,
});
