// src/components.jsx — shared primitives for Fuji presale (R2)
//  - Glossy Button (TrimRX-grade) with idle pulse, hover lift, active press
//  - ImagePlaceholder: smooth 3-stop cohort gradient in production, dev label only in op-mode
//  - Card-brand detection from PAN BIN (Codex MED2 / Kimi LOW)
//  - Logo, Chip, Icon, Card, ProgressBar, VariantTag

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC, useMemo: useMemoC } = React;
const BRAND_LOGO_URL = "";
const WORDMARK_LEFT = "Fuji";
const WORDMARK_ACCENT = "RX";

// ─────────────────────────────────────────────────────────────────────────────
// OPERATOR MODE - URL params and tweak controls are local-dev only.
// Read by cohort.jsx + this file's ImagePlaceholder + cockpit visibility default.
// ─────────────────────────────────────────────────────────────────────────────
function isDevOperatorHost() {
  if (typeof window === 'undefined') return false;
  const host = window.location.hostname;
  const loopback = [127, 0, 0, 1].join('.');
  return host === 'localhost' || host === loopback || host === '::1';
}

function getInitialOperatorMode() {
  if (!isDevOperatorHost()) return false;
  try {
    const p = new URLSearchParams(window.location.search);
    return (p.has('op') && p.get('op') !== '0') || p.get('operator') === '1';
  } catch { return false; }
}

// ─────────────────────────────────────────────────────────────────────────────
// LOGO
// ─────────────────────────────────────────────────────────────────────────────
function BrandLogo({ size = 22, muted = false }) {
  if (BRAND_LOGO_URL) {
    return (
      <img
        src={BRAND_LOGO_URL}
        alt="Fuji"
        style={{
          display: 'inline-flex',
          height: size,
          width: 'auto',
          maxWidth: size * 7,
          objectFit: 'contain',
          opacity: muted ? 0.72 : 1,
          lineHeight: 1,
          verticalAlign: 'middle',
        }}
      />
    );
  }

  return (
    <span style={{
      display: 'inline-flex', alignItems: 'baseline', gap: 0,
      fontFamily: 'var(--font-display)', fontWeight: 680,
      fontSize: size, letterSpacing: '-0.04em',
      color: muted ? 'var(--brand-text-muted)' : 'var(--brand-text)',
      lineHeight: 1,
    }}>
      <span>{WORDMARK_LEFT}</span>
      <span className="rx-accent" style={{
        fontFamily: 'var(--font-mono)',
        fontSize: size * 0.62, fontWeight: 600,
        letterSpacing: '0.04em',
        marginLeft: 2, marginRight: 1,
        padding: '2px 5px',
        background: 'var(--cohort-accent)',
        color: 'white',
        borderRadius: 5,
        transform: 'translateY(-2px)',
      }}>{WORDMARK_ACCENT}</span>
    </span>
  );
}

const ZeraLogo = BrandLogo;

// ─────────────────────────────────────────────────────────────────────────────
// BUTTON — Glossy TrimRX-grade primary; subtle pulse; hover lift; active press
// ─────────────────────────────────────────────────────────────────────────────
function Button({
  children, variant = 'primary', size = 'md',
  onClick, disabled, fullWidth,
  pulse = false, glossy = true,
  ...rest
}) {
  const [hover, setHover] = useStateC(false);
  const [active, setActive] = useStateC(false);

  const sizes = {
    sm: { padding: '8px 14px', fontSize: 13, height: 36, gap: 6 },
    md: { padding: '12px 20px', fontSize: 15, height: 'var(--touch-target-min)', gap: 8 },
    lg: { padding: '16px 26px', fontSize: 16, height: 'calc(var(--touch-target-min) + 8px)', gap: 10 },
    xl: { padding: '18px 32px', fontSize: 17, height: 'calc(var(--touch-target-min) + 14px)', gap: 12 },
  };

  const liftY = active ? '0px' : hover ? '-1px' : '0px';
  const scaleV = active ? 0.985 : 1;

  const variants = {
    primary: {
      background: glossy
        ? 'linear-gradient(180deg, hsl(var(--cohort-accent-hue) var(--cohort-accent-saturation) 64%) 0%, hsl(var(--cohort-accent-hue) var(--cohort-accent-saturation) 52%) 50%, hsl(var(--cohort-accent-hue) var(--cohort-accent-saturation) 44%) 100%)'
        : 'var(--cohort-accent)',
      color: 'white',
      border: '1px solid hsl(var(--cohort-accent-hue) var(--cohort-accent-saturation) 38%)',
      boxShadow: hover
        ? 'var(--shadow-glow-hover), 0 0 0 4px hsl(var(--cohort-accent-hue) var(--cohort-accent-saturation) 60% / 0.10)'
        : 'var(--shadow-glow)',
    },
    secondary: {
      background: 'var(--brand-bg-elev)',
      color: 'var(--brand-text)',
      border: '1px solid var(--brand-border)',
      boxShadow: hover ? 'var(--shadow-md)' : 'var(--shadow-sm)',
    },
    ghost: {
      background: hover ? 'var(--brand-bg-sunken)' : 'transparent',
      color: 'var(--brand-text)',
      border: '1px solid transparent',
    },
    outline: {
      background: hover ? 'var(--cohort-accent-soft)' : 'transparent',
      color: 'var(--cohort-accent-strong)',
      border: '1.5px solid var(--cohort-accent)',
    },
    danger: {
      background: 'var(--brand-bg-elev)',
      color: 'var(--brand-danger)',
      border: '1px solid var(--brand-border)',
    },
  };

  return (
    <button
      onClick={onClick}
      disabled={disabled}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setActive(false); }}
      onMouseDown={() => setActive(true)}
      onMouseUp={() => setActive(false)}
      onBlur={() => setActive(false)}
      style={{
        ...sizes[size],
        ...variants[variant],
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontWeight: 600, letterSpacing: '-0.005em',
        borderRadius: 'var(--radius-button)',
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.5 : 1,
        width: fullWidth ? '100%' : 'auto',
        position: 'relative',
        overflow: 'hidden',
        transform: `translateY(${liftY}) scale(${scaleV})`,
        transition: 'transform 160ms var(--easing-out), box-shadow 200ms var(--easing-out), background 200ms var(--easing-out), border-color var(--transition-ms) var(--easing-out)',
        animation: pulse && variant === 'primary' && !disabled ? 'cta-idle-pulse 5.5s ease-in-out infinite' : 'none',
      }}
      {...rest}
    >
      {/* Inner gloss highlight (only on primary glossy) */}
      {variant === 'primary' && glossy && (
        <span aria-hidden="true" style={{
          position: 'absolute', inset: 1, top: 1, height: '46%',
          background: 'linear-gradient(180deg, rgba(255,255,255,0.22) 0%, rgba(255,255,255,0) 100%)',
          borderRadius: 'calc(var(--radius-button) - 1px) calc(var(--radius-button) - 1px) 0 0',
          pointerEvents: 'none',
        }} />
      )}
      <ChildrenWithArrowLift hover={hover}>{children}</ChildrenWithArrowLift>
    </button>
  );
}

// Translates the arrow child slightly on hover (TrimRX micro-animation)
function ChildrenWithArrowLift({ hover, children }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      gap: 'inherit',
      position: 'relative', zIndex: 1,
    }}>
      {React.Children.map(children, (child) => {
        if (React.isValidElement(child) && child.type?.name === 'Icon' && child.props.kind === 'arrow') {
          return React.cloneElement(child, {
            style: {
              ...(child.props.style || {}),
              transform: hover ? 'translateX(3px)' : 'translateX(0)',
              transition: 'transform 200ms var(--easing-out)',
            },
          });
        }
        return child;
      })}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CHIP / BADGE
// ─────────────────────────────────────────────────────────────────────────────
function Chip({ children, tone = 'neutral', icon, size = 'md' }) {
  const tones = {
    neutral: { bg: 'var(--brand-bg-elev)', fg: 'var(--brand-text)', bd: 'var(--brand-border)' },
    accent:  { bg: 'var(--cohort-accent-soft)', fg: 'var(--cohort-accent-strong)', bd: 'var(--cohort-accent-line)' },
    teal:    { bg: 'var(--brand-secondary-soft)', fg: 'var(--brand-secondary)', bd: 'var(--brand-secondary)' },
    ghost:   { bg: 'transparent', fg: 'var(--brand-text-muted)', bd: 'var(--brand-border)' },
  };
  const t = tones[tone];
  const px = size === 'sm' ? '4px 8px' : '5px 10px';
  const fs = size === 'sm' ? 11 : 12;
  return (
    <span className="cohort-shift" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: px, fontSize: fs, fontWeight: 500,
      background: t.bg, color: t.fg,
      border: `1px solid ${t.bd}`,
      borderRadius: 999, lineHeight: 1.2,
      whiteSpace: 'nowrap',
    }}>
      {icon}
      {children}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// ICON
// ─────────────────────────────────────────────────────────────────────────────
function Icon({ kind, size = 18, color = 'currentColor', strokeWidth = 1.6, style }) {
  const p = {
    width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
    stroke: color, strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round',
    style,
  };
  switch (kind) {
    case 'shield':    return <svg {...p}><path d="M12 3l8 3v6c0 5-3.5 8.5-8 9-4.5-.5-8-4-8-9V6l8-3z"/></svg>;
    case 'lock':      return <svg {...p}><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V8a4 4 0 1 1 8 0v3"/></svg>;
    case 'check':     return <svg {...p}><path d="M4 12l5 5L20 6"/></svg>;
    case 'clipboard': return <svg {...p}><rect x="6" y="4" width="12" height="17" rx="2"/><path d="M9 4v3h6V4"/><path d="M9 11h6M9 15h4"/></svg>;
    case 'pill':      return <svg {...p}><rect x="3" y="9" width="18" height="6" rx="3" transform="rotate(-25 12 12)"/><path d="M9.5 6.5l7 7" /></svg>;
    case 'beaker':    return <svg {...p}><path d="M9 3v6l-5 9a2 2 0 0 0 1.8 3h12.4a2 2 0 0 0 1.8-3l-5-9V3"/><path d="M8 3h8"/></svg>;
    case 'arrow':     return <svg {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case 'spark':     return <svg {...p}><path d="M12 3v6M12 15v6M3 12h6M15 12h6M5.5 5.5l4 4M14.5 14.5l4 4M18.5 5.5l-4 4M9.5 14.5l-4 4"/></svg>;
    case 'doctor':    return <svg {...p}><circle cx="12" cy="8" r="4"/><path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6"/></svg>;
    case 'eye':       return <svg {...p}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'leaf':      return <svg {...p}><path d="M20 4c0 8-6 14-14 14C6 10 12 4 20 4z"/><path d="M14 10L4 20"/></svg>;
    case 'chev':      return <svg {...p}><path d="M9 6l6 6-6 6"/></svg>;
    case 'chev-down': return <svg {...p}><path d="M6 9l6 6 6-6"/></svg>;
    case 'x':         return <svg {...p}><path d="M6 6l12 12M18 6L6 18"/></svg>;
    case 'menu':      return <svg {...p}><path d="M4 7h16M4 12h16M4 17h16"/></svg>;
    case 'star':      return <svg {...p}><path d="M12 3l2.6 5.6 6.2.6-4.7 4.2 1.4 6L12 16.8 6.5 19.4l1.4-6L3.2 9.2l6.2-.6L12 3z"/></svg>;
    case 'clock':     return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case 'badge':     return <svg {...p}><path d="M12 2l3 2 3.5-.5 1 3.5 3 2-1.5 3.5L23 16l-2.5 2.5L20 22l-3.5-1L13 24l-2-3-3.5 1L6 18.5 3.5 16 5 12l-1.5-3.5L7 6.5 8 3l3.5.5L12 2z"/><path d="M9 12l2 2 4-4"/></svg>;
    default:          return <svg {...p}><circle cx="12" cy="12" r="9"/></svg>;
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// IMAGE PLACEHOLDER
//  - Operator mode: striped + mono cohort-key dev label (R1 default)
//  - Production mode: smooth 3-stop cohort gradient (R1 fix b531467 baked in)
// ─────────────────────────────────────────────────────────────────────────────
function ImagePlaceholder({ label, cohortKey, aspect = '4/5', tone = 'neutral', operatorMode = false }) {
  const palettes = {
    neutral:    ['hsl(248 26% 95%)', 'hsl(248 30% 85%)', 'hsl(248 38% 72%)'],
    'f-3044':   ['hsl(340 38% 96%)', 'hsl(340 42% 86%)', 'hsl(340 48% 72%)'],
    'm-3044':   ['hsl(218 36% 95%)', 'hsl(218 40% 84%)', 'hsl(218 48% 70%)'],
    'f-4559':   ['hsl(340 26% 96%)', 'hsl(340 30% 88%)', 'hsl(22 38% 78%)'],
    'm-4559':   ['hsl(218 24% 95%)', 'hsl(218 30% 87%)', 'hsl(220 38% 72%)'],
    'f-1829':   ['hsl(340 60% 96%)', 'hsl(340 65% 84%)', 'hsl(280 55% 72%)'],
    'm-1829':   ['hsl(218 60% 96%)', 'hsl(218 65% 82%)', 'hsl(180 55% 65%)'],
    'f-60':     ['hsl(340 18% 96%)', 'hsl(28 22% 90%)',  'hsl(28 28% 78%)'],
    'm-60':     ['hsl(218 16% 95%)', 'hsl(220 20% 86%)', 'hsl(220 24% 72%)'],
    clinical:   ['hsl(174 26% 96%)', 'hsl(174 30% 86%)', 'hsl(248 36% 76%)'],
    warm:       ['hsl(28 50% 96%)',  'hsl(28 55% 86%)',  'hsl(348 50% 74%)'],
  };
  const [c1, c2, c3] = palettes[tone] || palettes.neutral;

  return (
    <div className="cohort-shift" style={{
      position: 'relative', aspectRatio: aspect, width: '100%',
      background: operatorMode
        ? `repeating-linear-gradient(135deg, ${c1} 0 14px, ${c2} 14px 28px)`
        : `linear-gradient(135deg, ${c1} 0%, ${c2} 45%, ${c3} 100%)`,
      borderRadius: 'var(--radius-card)',
      border: '1px solid var(--brand-border)',
      overflow: 'hidden',
      display: 'flex', alignItems: 'flex-end', padding: 14,
    }}>
      {/* Subtle production gloss — adds depth in production mode */}
      {!operatorMode && (
        <span aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(ellipse at 30% 25%, rgba(255,255,255,0.25) 0%, rgba(255,255,255,0) 55%)',
          pointerEvents: 'none',
        }} />
      )}
      {/* Dev label — only visible in operator mode */}
      {operatorMode && (
        <div style={{
          position: 'relative', zIndex: 1,
          fontFamily: 'var(--font-mono)', fontSize: 10.5,
          background: 'rgba(11,15,26,0.78)', color: '#E8ECF3',
          padding: '5px 8px', borderRadius: 6, letterSpacing: 0.2,
          display: 'flex', flexDirection: 'column', gap: 2,
        }}>
          <span style={{ opacity: 0.55, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.1em' }}>
            // image_slot
          </span>
          <span>{label}</span>
          {cohortKey && <span style={{ opacity: 0.65 }}>cohort={cohortKey}</span>}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CARD
// ─────────────────────────────────────────────────────────────────────────────
function Card({ children, padding = 24, style = {}, ...rest }) {
  return (
    <div className="cohort-shift" style={{
      background: 'var(--brand-bg-elev)',
      border: '1px solid var(--brand-border)',
      borderRadius: 'var(--radius-card)',
      padding, ...style,
    }} {...rest}>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PROGRESS BAR
// ─────────────────────────────────────────────────────────────────────────────
function ProgressBar({ value, max = 100, height = 4 }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div role="progressbar" aria-valuenow={value} aria-valuemax={max} aria-valuemin={0} style={{
      width: '100%', height, background: 'var(--brand-bg-sunken)',
      borderRadius: 999, overflow: 'hidden', position: 'relative',
    }}>
      <div style={{
        width: `${pct}%`, height: '100%',
        background: 'linear-gradient(90deg, var(--cohort-accent), var(--brand-secondary))',
        borderRadius: 999,
        transition: 'width 600ms cubic-bezier(0.16, 1, 0.3, 1)',
      }} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// VARIANT TAG (only renders in operator mode)
// ─────────────────────────────────────────────────────────────────────────────
function VariantTag({ id, visible = true }) {
  if (!visible) return null;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontFamily: 'var(--font-mono)', fontSize: 9.5,
      padding: '2px 6px', background: 'var(--brand-bg-sunken)',
      color: 'var(--brand-text-soft)',
      border: '1px solid var(--brand-border)',
      borderRadius: 4, letterSpacing: '0.04em',
    }}>
      <span style={{ width: 4, height: 4, borderRadius: 999, background: 'var(--cohort-accent)' }} />
      bandit:{id}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CARD-BRAND DETECTION from PAN BIN (Codex MED2 / Kimi LOW)
// ─────────────────────────────────────────────────────────────────────────────
function detectCardBrand(numString) {
  const n = (numString || '').replace(/\D/g, '');
  if (!n) return null;
  if (/^4/.test(n))                       return 'VISA';
  if (/^(5[1-5]|2[2-7])/.test(n))         return 'MC';
  if (/^3[47]/.test(n))                   return 'AMEX';
  if (/^(6011|65|64[4-9]|622)/.test(n))   return 'DISCOVER';
  if (/^(30[0-5]|36|38|39)/.test(n))      return 'DINERS';
  if (/^35(2[89]|[3-8])/.test(n))         return 'JCB';
  return null;
}

// ─────────────────────────────────────────────────────────────────────────────
// USEMEDIA hook — replaces window.matchMedia boilerplate
// ─────────────────────────────────────────────────────────────────────────────
function useMedia(query) {
  const [matches, setMatches] = useStateC(() =>
    typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(query).matches : false
  );
  useEffectC(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return;
    const m = window.matchMedia(query);
    const fn = (e) => setMatches(e.matches);
    setMatches(m.matches);
    m.addEventListener?.('change', fn);
    return () => m.removeEventListener?.('change', fn);
  }, [query]);
  return matches;
}

function useScrolledPast(threshold) {
  const [past, setPast] = useStateC(false);
  useEffectC(() => {
    const fn = () => setPast(window.scrollY > threshold);
    fn();
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, [threshold]);
  return past;
}

Object.assign(window, {
  BrandLogo, ZeraLogo, Button, Chip, Icon, ImagePlaceholder, Card, ProgressBar, VariantTag,
  detectCardBrand, useMedia, useScrolledPast, isDevOperatorHost, getInitialOperatorMode,
});
