// Pipewerk — brand foundation: logo system, palette, typography
// Original mark inspired by horizontal-line sphere ("pipe cross-section meets planet")

const PW_COLORS = {
  ink: "#1a1d1b",
  // dark mode: a single warm-green coal, low contrast on softened paper
  coal: "#1e2724",
  coalUp: "#262f2b",
  paperDark: "#d9d6cd",  // softened foreground on coal — not pure white
  paper: "#f6f6f4",
  stone: "#e8e6e0",
  // ONE signature green for UI. (The mark itself keeps its mint→forest gradient.)
  forest: "#143a2d",
  green: "#1f7a52",
  mint: "#3ed598",       // RESERVED for the logo gradient only — do not use in UI
  fog: "#9aa19c",
};

// ---------- LOGO MARK ----------
// A circle masked by horizontal "pipe" stripes of varying length, anchored to a vertical pipe-line.
// Stripe lengths follow a sine-eased curve so they read as a sphere.
function PWMark({ size = 96, gradient = true, color, monochrome = false, anchor }) {
  // Read anchor default from tweaks context if not explicitly set
  const ctx = window.PWTweaksContext ? React.useContext(window.PWTweaksContext) : null;
  if (anchor === undefined) {
    const map = { anchored: "attached", detached: "gap", free: "none" };
    anchor = ctx && map[ctx.markShape] ? map[ctx.markShape] : "attached";
  }
  const cx = 50, cy = 50, r = 38;
  const rows = 8;
  const gap = 2.8; // px in viewBox between stripes
  const rowH = (r * 2 - gap * (rows - 1)) / rows;
  const stripes = [];
  for (let i = 0; i < rows; i++) {
    const y = cy - r + i * (rowH + gap);
    // chord half-length at this y for a perfect circle:
    const dy = (y + rowH / 2) - cy;
    const half = Math.sqrt(Math.max(0, r * r - dy * dy));
    // tiny inset so stripes don't kiss the circle edge — symmetric, true circle
    const shorten = 1;
    const x1 = cx - half + shorten;
    const x2 = cx + half - shorten;
    stripes.push({ y, x1, x2, rowH });
  }
  // tinted gradient: when a brand color is passed, derive a light→mid→deep ramp from it
  const useTint = !!color && !monochrome;
  const id = `pwgrad-${size}-${gradient ? 1 : 0}-${useTint ? color.replace("#","") : (monochrome ? "m" : "d")}`;
  const stops = useTint
    ? [
        { o: "0%",   c: `color-mix(in oklab, ${color} 45%, #ffffff)` },
        { o: "55%",  c: color },
        { o: "100%", c: `color-mix(in oklab, ${color} 65%, ${PW_COLORS.ink})` },
      ]
    : [
        { o: "0%",   c: PW_COLORS.mint },
        { o: "55%",  c: PW_COLORS.green },
        { o: "100%", c: PW_COLORS.forest },
      ];
  const stroke = monochrome ? (color || "currentColor") : `url(#${id})`;
  const anchorFill = monochrome
    ? (color || "currentColor")
    : (useTint ? `color-mix(in oklab, ${color} 70%, ${PW_COLORS.ink})` : PW_COLORS.forest);
  return (
    <svg viewBox="0 0 100 100" width={size} height={size} style={{ display: "block" }}>
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="1" y2="1">
          {stops.map((s, i) => <stop key={i} offset={s.o} stopColor={s.c} />)}
        </linearGradient>
      </defs>
      {/* vertical anchor — the "pipe" the stripes flow from. Variants: attached, gap, none */}
      {anchor !== "none" && (
        <rect
          x={anchor === "gap" ? cx - r - 4.5 : cx - r - 0.5}
          y={cy - r + 1}
          width="1.6"
          height={r * 2 - 2}
          fill={anchorFill}
          opacity={anchor === "gap" ? 0.5 : 0.85}
          rx="0.8"
        />
      )}
      <g>
        {stripes.map((s, i) => (
          <rect
            key={i}
            x={s.x1}
            y={s.y}
            width={Math.max(0.4, s.x2 - s.x1)}
            height={s.rowH}
            rx={s.rowH / 2}
            fill={stroke}
          />
        ))}
      </g>
    </svg>
  );
}

// ---------- WORDMARK ----------
// Custom-tuned wordmark in Geist with tighter tracking + a single ligature feel
function PWWordmark({ size = 56, color = PW_COLORS.ink }) {
  return (
    <span
      style={{
        fontFamily: "'Geist', system-ui, sans-serif",
        fontWeight: 600,
        fontSize: size,
        letterSpacing: "-0.045em",
        color,
        lineHeight: 1,
        display: "inline-block",
      }}
    >
      pipewerk
    </span>
  );
}

// ---------- HORIZONTAL LOCKUP ----------
function PWLockup({ size = 56, color = PW_COLORS.ink, mono = false }) {
  // mark dominates; wordmark sits ~80% of mark height.
  // Gap matches prototype.html nav-logo ratio (12px / 22px ≈ 0.55 of wordmark height,
  // which is size * 0.84 → gap = size * 0.46).
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: size * 0.46 }}>
      <PWMark size={size * 1.35} monochrome={mono} color={mono ? color : undefined} />
      <PWWordmark size={size * 0.84} color={color} />
    </div>
  );
}

// ---------- STACKED LOCKUP ----------
function PWStacked({ size = 64, color = PW_COLORS.ink, mono = false }) {
  return (
    <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: size * 0.25 }}>
      <PWMark size={size * 1.6} monochrome={mono} color={mono ? color : undefined} />
      <PWWordmark size={size} color={color} />
    </div>
  );
}

// ---------- MONOGRAM ----------
// Square mark with the sphere inset — for app icons, favicons, social avatars
function PWMonogram({ size = 96, bg = PW_COLORS.ink, fg = "gradient" }) {
  return (
    <div
      style={{
        width: size,
        height: size,
        background: bg,
        borderRadius: size * 0.22,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        position: "relative",
        overflow: "hidden",
      }}
    >
      <PWMark size={size * 0.66} monochrome={fg !== "gradient"} color={fg !== "gradient" ? fg : undefined} />
    </div>
  );
}

// ---------- COLOR SWATCH ----------
function Swatch({ name, hex, role, dark = false }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <div
        style={{
          background: hex,
          aspectRatio: "1.3 / 1",
          borderRadius: 10,
          border: `1px solid ${dark ? "#222" : "rgba(0,0,0,0.06)"}`,
        }}
      />
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, opacity: 0.55, letterSpacing: "0.04em", textTransform: "uppercase" }}>{role}</div>
        <div style={{ fontFamily: "'Geist', sans-serif", fontSize: 14, fontWeight: 500 }}>{name}</div>
        <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, opacity: 0.5 }}>{hex.toUpperCase()}</div>
      </div>
    </div>
  );
}

Object.assign(window, { PW_COLORS, PWMark, PWWordmark, PWLockup, PWStacked, PWMonogram, Swatch });
