// Reusable visual primitives for Pivot Parking app
// (Logo, barcode, pass card, button, modal, toast)

const P = window.PIVOT;

// ── Logo ─────────────────────────────────────────────────────────────────
function PivotLogo({ size = 28, light = false }) {
  const cyan = P.cyan;
  const ink  = light ? '#FFFFFF' : P.navy;
  // Stylized recreation of the pivotparking mark — wordmark + curved arrows.
  return (
    <svg width={size * 3.4} height={size} viewBox="0 0 170 50" style={{ display: 'block' }}>
      {/* upper arrow arcing right */}
      <path d="M 28 6 Q 90 -6 142 10 L 138 18 L 152 14 L 146 2"
            fill="none" stroke={ink} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"
            transform="translate(0,1)"/>
      {/* lower arrow arcing left */}
      <path d="M 142 44 Q 80 56 28 40 L 32 32 L 18 36 L 24 48"
            fill="none" stroke={cyan} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/>
      {/* PIVOT */}
      <text x="85" y="27" textAnchor="middle"
            fontFamily="-apple-system, system-ui, 'SF Pro Display', sans-serif"
            fontWeight="900" fontSize="18" fill={cyan} letterSpacing="0.5">PIVOT</text>
      {/* PARKING */}
      <text x="85" y="40" textAnchor="middle"
            fontFamily="-apple-system, system-ui, 'SF Pro Display', sans-serif"
            fontWeight="800" fontSize="9.5" fill={ink} letterSpacing="2.6">PARKING</text>
    </svg>
  );
}

// ── Barcode (real Code 128) ──────────────────────────────────────────────
function Barcode({ value, height = 110, scale = 2.2, color = '#0A0F1C' }) {
  const widths = React.useMemo(() => window.CODE128(value), [value]);
  let x = 0;
  const els = widths.map((seg, i) => {
    const w = seg.w * scale;
    const rect = seg.bar ? (
      <rect key={i} x={x} y={0} width={w} height={height} fill={color}/>
    ) : null;
    x += w;
    return rect;
  });
  return (
    <svg width={x} height={height} viewBox={`0 0 ${x} ${height}`} style={{ display: 'block' }}>
      {els}
    </svg>
  );
}

// ── Buttons ──────────────────────────────────────────────────────────────
function PivotButton({
  children, onClick, variant = 'primary', size = 'md',
  fullWidth = false, icon, disabled = false, style = {},
}) {
  const sizes = {
    sm: { h: 36, px: 14, fs: 14, gap: 6 },
    md: { h: 48, px: 18, fs: 15, gap: 8 },
    lg: { h: 56, px: 22, fs: 17, gap: 10 },
  }[size];
  const variants = {
    primary: {
      background: P.cyan, color: '#fff',
      boxShadow: '0 4px 14px rgba(11,165,199,0.35), inset 0 -2px 0 rgba(0,0,0,0.08)',
    },
    secondary: {
      background: P.navy, color: '#fff',
      boxShadow: '0 4px 14px rgba(12,35,64,0.25)',
    },
    ghost: {
      background: 'transparent', color: P.navy,
      boxShadow: `inset 0 0 0 1.5px ${P.line}`,
    },
    danger: {
      background: '#fff', color: '#B91C1C',
      boxShadow: 'inset 0 0 0 1.5px rgba(185,28,28,0.25)',
    },
    amber: {
      background: P.amber, color: P.navy,
      boxShadow: '0 4px 14px rgba(245,166,35,0.3), inset 0 -2px 0 rgba(0,0,0,0.08)',
    },
  }[variant];
  return (
    <button onClick={disabled ? undefined : onClick} disabled={disabled} style={{
      height: sizes.h, padding: `0 ${sizes.px}px`, gap: sizes.gap,
      fontSize: sizes.fs, fontWeight: 700, letterSpacing: -0.1,
      border: 0, borderRadius: 14,
      width: fullWidth ? '100%' : undefined,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      cursor: disabled ? 'not-allowed' : 'pointer',
      opacity: disabled ? 0.5 : 1,
      fontFamily: 'inherit',
      transition: 'transform 0.08s ease',
      ...variants, ...style,
    }}
    onMouseDown={e => e.currentTarget.style.transform = 'scale(0.98)'}
    onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
      {icon}{children}
    </button>
  );
}

// ── Status pill ──────────────────────────────────────────────────────────
function StatusPill({ status }) {
  const map = {
    available: { bg: '#DCFCE7', fg: '#166534', label: 'Available' },
    used:      { bg: '#FEE2E2', fg: '#991B1B', label: 'Used' },
    shared:    { bg: '#DBEAFE', fg: '#1E3A8A', label: 'Shared' },
  };
  const s = map[status] || map.available;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '3px 9px', borderRadius: 999,
      background: s.bg, color: s.fg,
      fontSize: 11, fontWeight: 700, letterSpacing: 0.3,
      textTransform: 'uppercase',
    }}>{s.label}</span>
  );
}

// ── Pass ticket (the actual cropped pass — what user sees) ───────────────
function PassTicket({ pass, size = 'md', faded = false }) {
  const dims = {
    sm: { w: 280, barH: 60, scale: 1.4, pad: 14, fs: 11, code: 14 },
    md: { w: 340, barH: 90, scale: 1.9, pad: 18, fs: 13, code: 18 },
    lg: { w: 360, barH: 130, scale: 2.4, pad: 22, fs: 14, code: 22 },
  }[size];
  return (
    <div style={{
      width: dims.w, background: '#fff', borderRadius: 18,
      padding: dims.pad, boxSizing: 'border-box',
      boxShadow: '0 1px 2px rgba(12,35,64,0.06), 0 12px 28px rgba(12,35,64,0.10)',
      position: 'relative', overflow: 'hidden',
      opacity: faded ? 0.6 : 1,
    }}>
      {/* Notches (ticket perforations) */}
      <div style={{
        position: 'absolute', left: -8, top: '60%', width: 16, height: 16,
        borderRadius: '50%', background: P.paper,
      }}/>
      <div style={{
        position: 'absolute', right: -8, top: '60%', width: 16, height: 16,
        borderRadius: '50%', background: P.paper,
      }}/>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4, gap: 8 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ color: P.navy, fontWeight: 800, fontSize: dims.fs + 2, letterSpacing: -0.2,
                        lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {pass.location}
          </div>
          <div style={{ color: P.muted, fontSize: dims.fs - 1, marginTop: 2,
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {pass.address}
          </div>
        </div>
        <PivotLogo size={18} />
      </div>
      {/* Validator */}
      <div style={{
        marginTop: 10,
        fontSize: dims.fs - 2, color: P.muted,
        textTransform: 'uppercase', letterSpacing: 1,
        fontWeight: 600,
      }}>
        Validator · {pass.validator}
      </div>
      {/* Barcode */}
      <div style={{
        marginTop: 12, padding: '12px 8px', background: '#fff',
        display: 'flex', justifyContent: 'center', alignItems: 'center',
        borderTop: `1px dashed ${P.line}`, borderBottom: `1px dashed ${P.line}`,
      }}>
        <Barcode value={pass.code} height={dims.barH} scale={dims.scale} color={P.ink}/>
      </div>
      {/* Code + expiration */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
        <div style={{
          fontFamily: '"SF Mono", ui-monospace, Menlo, monospace',
          fontWeight: 700, fontSize: dims.code, color: P.ink, letterSpacing: 1.5,
        }}>{pass.code}</div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: dims.fs - 2, color: P.muted, textTransform: 'uppercase', letterSpacing: 1 }}>Expires</div>
          <div style={{ fontSize: dims.fs, color: P.navy, fontWeight: 700 }}>{pass.expires}</div>
        </div>
      </div>
    </div>
  );
}

// ── Toast ────────────────────────────────────────────────────────────────
function Toast({ message, kind = 'success', onDone }) {
  React.useEffect(() => {
    const t = setTimeout(onDone, 2400);
    return () => clearTimeout(t);
  }, [onDone]);
  const colors = {
    success: { bg: P.navy, fg: '#fff', dot: '#22D38A' },
    info:    { bg: P.navy, fg: '#fff', dot: P.cyan },
    warn:    { bg: '#7C2D12', fg: '#fff', dot: '#FBBF24' },
  }[kind];
  return (
    <div style={{
      position: 'absolute', bottom: 50, left: '50%', transform: 'translateX(-50%)',
      background: colors.bg, color: colors.fg,
      padding: '12px 18px', borderRadius: 14,
      display: 'flex', alignItems: 'center', gap: 10,
      fontSize: 14, fontWeight: 600,
      boxShadow: '0 12px 30px rgba(0,0,0,0.25)',
      animation: 'pivotToastIn 0.25s ease',
      zIndex: 100, whiteSpace: 'nowrap',
    }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: colors.dot }}/>
      {message}
    </div>
  );
}

// ── Modal sheet (mobile bottom sheet) ────────────────────────────────────
function Sheet({ open, onClose, children, title }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: 'rgba(8,18,36,0.45)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'pivotFade 0.18s ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff', width: '100%',
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '8px 18px 30px', boxSizing: 'border-box',
        animation: 'pivotSlideUp 0.22s cubic-bezier(.22,.9,.32,1)',
      }}>
        <div style={{
          width: 40, height: 5, background: '#D8DEE7',
          borderRadius: 4, margin: '8px auto 16px',
        }}/>
        {title && (
          <div style={{
            fontSize: 19, fontWeight: 800, color: P.navy,
            marginBottom: 14, letterSpacing: -0.3,
          }}>{title}</div>
        )}
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { PivotLogo, Barcode, PivotButton, StatusPill, PassTicket, Toast, Sheet });
