// Shared UI primitives + a couple of decorative SVGs (geometric cookies only).
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// Responsive helper — branches layouts at narrow widths.
function useIsMobile(breakpoint = 760) {
  const [m, setM] = useState(() => typeof window !== "undefined" && window.innerWidth < breakpoint);
  useEffect(() => {
    const on = () => setM(window.innerWidth < breakpoint);
    window.addEventListener("resize", on);
    return () => window.removeEventListener("resize", on);
  }, [breakpoint]);
  return m;
}

// ───────────────────────────────────────────────────────────────────────────
// Cookie — flat, geometric. A warm circle with a ring of "icing" and dots.
// No hand-drawn illustration; this is just a simple decorative motif.
// ───────────────────────────────────────────────────────────────────────────
function Cookie({ size = 72, ring = "oklch(0.92 0.04 80)", dough = "oklch(0.78 0.06 70)", dots = "oklch(0.55 0.14 25)", rotate = 0, dotCount = 6, style }) {
  const r = size / 2;
  const ringR = r - size * 0.12;
  const dotR = size * 0.045;
  const dotsArr = Array.from({ length: dotCount }, (_, i) => {
    const a = (i / dotCount) * Math.PI * 2;
    const rr = ringR - size * 0.1;
    return { x: r + Math.cos(a) * rr, y: r + Math.sin(a) * rr };
  });
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: `rotate(${rotate}deg)`, ...style }}>
      <circle cx={r} cy={r} r={r - 1} fill={dough} />
      <circle cx={r} cy={r} r={ringR} fill="none" stroke={ring} strokeWidth={size * 0.05} />
      {dotsArr.map((d, i) => (
        <circle key={i} cx={d.x} cy={d.y} r={dotR} fill={dots} />
      ))}
    </svg>
  );
}

// Wavy hand-drawn underline (geometric, not illustrative)
function Squiggle({ width = 120, height = 12, color = "var(--terra)", stroke = 2 }) {
  const path = `M 2 ${height/2} Q ${width*0.15} 2, ${width*0.3} ${height/2} T ${width*0.6} ${height/2} T ${width*0.9} ${height/2} T ${width-2} ${height/2}`;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: "block" }}>
      <path d={path} fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" />
    </svg>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Form atoms
// ───────────────────────────────────────────────────────────────────────────
function Label({ children, required, hint }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 10 }}>
      <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: 0.1 }}>
        {children}
        {required && <span style={{ color: "var(--terra)", marginLeft: 4 }}>*</span>}
      </div>
      {hint && <div style={{ fontSize: 13, color: "var(--cocoa-soft)", lineHeight: 1.45 }}>{hint}</div>}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, type = "text", error, ...rest }) {
  return (
    <input
      type={type}
      value={value ?? ""}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: "100%",
        background: "var(--butter)",
        border: `1px solid ${error ? "var(--berry)" : "var(--rule)"}`,
        borderRadius: 10,
        padding: "12px 14px",
        fontSize: 15,
        outline: "none",
        transition: "border-color 120ms ease, box-shadow 120ms ease",
      }}
      onFocus={(e) => { e.currentTarget.style.borderColor = "var(--terra)"; e.currentTarget.style.boxShadow = "0 0 0 3px oklch(0.65 0.14 45 / 0.15)"; }}
      onBlur={(e) => { e.currentTarget.style.borderColor = error ? "var(--berry)" : "var(--rule)"; e.currentTarget.style.boxShadow = "none"; }}
      {...rest}
    />
  );
}

function Textarea({ value, onChange, placeholder, rows = 3, error }) {
  return (
    <textarea
      value={value ?? ""}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      rows={rows}
      style={{
        width: "100%",
        background: "var(--butter)",
        border: `1px solid ${error ? "var(--berry)" : "var(--rule)"}`,
        borderRadius: 10,
        padding: "12px 14px",
        fontSize: 15,
        outline: "none",
        resize: "vertical",
        lineHeight: 1.5,
        fontFamily: "inherit",
      }}
      onFocus={(e) => { e.currentTarget.style.borderColor = "var(--terra)"; e.currentTarget.style.boxShadow = "0 0 0 3px oklch(0.65 0.14 45 / 0.15)"; }}
      onBlur={(e) => { e.currentTarget.style.borderColor = error ? "var(--berry)" : "var(--rule)"; e.currentTarget.style.boxShadow = "none"; }}
    />
  );
}

// Pill-style radio for big picks
function PillOption({ selected, onClick, title, sub, accent }) {
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        textAlign: "left",
        width: "100%",
        background: selected ? "var(--butter)" : "transparent",
        border: `1.5px solid ${selected ? "var(--terra)" : "var(--rule)"}`,
        borderRadius: 14,
        padding: "14px 16px",
        cursor: "pointer",
        transition: "all 140ms ease",
        boxShadow: selected ? "0 0 0 3px oklch(0.65 0.14 45 / 0.12)" : "none",
        display: "flex",
        alignItems: "flex-start",
        gap: 12,
      }}
    >
      <div
        aria-hidden
        style={{
          width: 18, height: 18, borderRadius: 999,
          border: `1.5px solid ${selected ? "var(--terra)" : "var(--rule)"}`,
          background: selected ? "var(--terra)" : "transparent",
          boxShadow: selected ? "inset 0 0 0 3px var(--butter)" : "none",
          flexShrink: 0,
          marginTop: 2,
        }}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 500, color: "var(--cocoa)", display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          {title}
          {accent && <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 999, background: accent.bg, color: accent.fg, fontWeight: 500, letterSpacing: 0.3, textTransform: "uppercase" }}>{accent.label}</span>}
        </div>
        {sub && <div style={{ fontSize: 13.5, color: "var(--cocoa-soft)", marginTop: 4, lineHeight: 1.45 }}>{sub}</div>}
      </div>
    </button>
  );
}

// Primary CTA
function Button({ children, onClick, variant = "primary", disabled, type = "button", style }) {
  const styles = {
    primary: {
      background: "var(--terra)",
      color: "var(--butter)",
      border: "1px solid var(--terra)",
    },
    ghost: {
      background: "transparent",
      color: "var(--cocoa)",
      border: "1px solid var(--rule)",
    },
    inkwell: {
      background: "var(--cocoa)",
      color: "var(--butter)",
      border: "1px solid var(--cocoa)",
    },
  }[variant];
  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      style={{
        ...styles,
        padding: "12px 22px",
        borderRadius: 999,
        fontSize: 14.5,
        fontWeight: 500,
        letterSpacing: 0.2,
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.45 : 1,
        transition: "transform 100ms ease, box-shadow 140ms ease, background 140ms ease",
        ...style,
      }}
      onMouseDown={(e) => { if (!disabled) e.currentTarget.style.transform = "translateY(1px)"; }}
      onMouseUp={(e) => { e.currentTarget.style.transform = "translateY(0)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; }}
    >
      {children}
    </button>
  );
}

// Error pill under a field
function FieldError({ children }) {
  if (!children) return null;
  return (
    <div style={{ marginTop: 8, fontSize: 13, color: "var(--berry)", display: "flex", alignItems: "center", gap: 6 }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--berry)", display: "inline-block" }} />
      {children}
    </div>
  );
}

Object.assign(window, { Cookie, Squiggle, Label, TextInput, Textarea, PillOption, Button, FieldError, useIsMobile });
