// arcai-components.jsx — Shared design system components

// ── Pill / Chip ──────────────────────────────────────────────────────────
function StreakChip({ days }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      width: 'fit-content', justifySelf: 'start', alignSelf: 'center',
      background: 'rgba(255,196,0,0.15)', color: 'var(--streak)',
      padding: '4px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700,
      fontFamily: 'var(--font-body)', whiteSpace: 'nowrap'
    }}>
      <span style={{ animation: 'flicker 1.6s ease-in-out infinite', display: 'inline-block' }}>🔥</span>
      {days} hari
    </span>
  );
}

function XPChip({ xp, animating }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      width: 'fit-content', justifySelf: 'start', alignSelf: 'center',
      background: 'rgba(212,255,58,0.15)', color: 'var(--accent)',
      padding: '4px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700,
      fontFamily: 'var(--font-body)', whiteSpace: 'nowrap',
      animation: animating ? 'xpburst 0.9s cubic-bezier(0.34,1.56,0.64,1) forwards' : 'none',
    }}>
      ⚡ {xp}
    </span>
  );
}

function EyebrowChip({ children, style }) {
  return (
    <span style={{
      display: 'inline-block',
      width: 'fit-content', justifySelf: 'start', alignSelf: 'center',
      background: 'rgba(212,255,58,0.08)', color: 'var(--accent)',
      border: '1px solid var(--border)',
      padding: '4px 10px', borderRadius: 999,
      fontSize: 11, fontWeight: 700, letterSpacing: '0.1em',
      textTransform: 'uppercase', fontFamily: 'var(--font-body)',
      whiteSpace: 'nowrap',
      ...style
    }}>{children}</span>
  );
}

function LevelChip({ level, label }) {
  const intensities = ['','rgba(212,255,58,0.12)','rgba(212,255,58,0.2)','rgba(212,255,58,0.3)','rgba(212,255,58,0.4)','rgba(212,255,58,0.5)'];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      width: 'fit-content', justifySelf: 'start', alignSelf: 'center',
      background: intensities[level] || intensities[2],
      color: 'var(--accent)', padding: '4px 10px',
      borderRadius: 999, fontSize: 11, fontWeight: 700,
      letterSpacing: '0.08em', textTransform: 'uppercase',
      fontFamily: 'var(--font-body)', border: '1px solid rgba(212,255,58,0.2)',
      whiteSpace: 'nowrap'
    }}>
      LEVEL {level}{label ? ` · ${label}` : ''}
    </span>
  );
}

function StatusChip({ status }) {
  const map = {
    success: { bg: 'rgba(123,237,111,0.15)', color: '#7BED6F', label: 'Benar' },
    partial: { bg: 'rgba(255,196,0,0.15)', color: '#FFC400', label: 'Sebagian' },
    retry:   { bg: 'rgba(255,75,145,0.15)', color: '#FF4B91', label: 'Coba Lagi' },
  };
  const s = map[status] || map.success;
  return (
    <span style={{
      display: 'inline-block',
      width: 'fit-content', justifySelf: 'start', alignSelf: 'center',
      background: s.bg, color: s.color,
      padding: '4px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700,
      whiteSpace: 'nowrap'
    }}>{s.label}</span>
  );
}

// ── Button ───────────────────────────────────────────────────────────────
function BtnPrimary({ children, onClick, disabled, fullWidth, size = 'lg' }) {
  const [pressed, setPressed] = React.useState(false);
  const pad = size === 'lg' ? '14px 24px' : '10px 18px';
  const fs = size === 'lg' ? 15 : 14;
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      onTouchStart={() => setPressed(true)}
      onTouchEnd={() => setPressed(false)}
      style={{
        background: disabled ? 'rgba(212,255,58,0.25)' : 'var(--accent)',
        color: 'var(--bg)', fontWeight: 700, fontFamily: 'var(--font-body)',
        fontSize: fs, padding: pad, borderRadius: 14, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
        boxShadow: disabled ? 'none' : pressed ? '0 1px 0 var(--accent-deep)' : '0 4px 0 var(--accent-deep)',
        transform: pressed ? 'translateY(3px)' : 'translateY(0)',
        transition: 'transform 0.1s, box-shadow 0.1s',
        width: fullWidth ? '100%' : 'auto',
        opacity: disabled ? 0.4 : 1,
        letterSpacing: '-0.01em',
      }}
    >{children}</button>
  );
}

function BtnGhost({ children, onClick, danger, small }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: hover ? (danger ? 'rgba(255,75,145,0.08)' : 'var(--surface-2)') : 'transparent',
        color: danger ? 'var(--danger)' : 'var(--text-muted)',
        border: `1px solid ${danger ? 'rgba(255,75,145,0.3)' : 'var(--border-strong)'}`,
        fontWeight: 600, fontFamily: 'var(--font-body)',
        fontSize: small ? 13 : 14, padding: small ? '8px 14px' : '11px 18px',
        borderRadius: 12, cursor: 'pointer',
        transition: 'background 0.15s, color 0.15s',
      }}
    >{children}</button>
  );
}

// ── Progress Bar ─────────────────────────────────────────────────────────
function ProgressBar({ value, max = 100, height = 6, style }) {
  const pct = Math.min(100, Math.max(0, (value / max) * 100));
  return (
    <div style={{ height, background: 'var(--surface-2)', borderRadius: 6, overflow: 'hidden', ...style }}>
      <div style={{
        height: '100%',
        width: `${pct}%`,
        background: 'linear-gradient(90deg, var(--accent-deep), var(--accent))',
        borderRadius: 6,
        transition: 'width 0.6s cubic-bezier(0.34,1.56,0.64,1)',
      }} />
    </div>
  );
}

// ── Radar Chart ──────────────────────────────────────────────────────────
function RadarChart({ data, size = 200, animated }) {
  // data: [{label, value (0-1)}] — 5 points
  const cx = size / 2, cy = size / 2, r = size * 0.38;
  const n = data.length;
  const [progress, setProgress] = React.useState(animated ? 0 : 1);

  React.useEffect(() => {
    if (!animated) return;
    let start = null;
    const dur = 900;
    const frame = (ts) => {
      if (!start) start = ts;
      const t = Math.min(1, (ts - start) / dur);
      setProgress(t);
      if (t < 1) requestAnimationFrame(frame);
    };
    const id = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(id);
  }, [animated]);

  const angle = (i) => (Math.PI * 2 * i) / n - Math.PI / 2;
  const pt = (i, val) => {
    const a = angle(i);
    const rv = val * r * progress;
    return [cx + rv * Math.cos(a), cy + rv * Math.sin(a)];
  };
  const labelPt = (i) => {
    const a = angle(i);
    const lr = r + 22;
    return [cx + lr * Math.cos(a), cy + lr * Math.sin(a)];
  };

  // grid circles
  const gridLevels = [0.25, 0.5, 0.75, 1];
  const gridPoly = (level) => {
    return Array.from({ length: n }, (_, i) => {
      const [x, y] = pt(i, level);
      return `${x},${y}`;
    }).join(' ');
  };

  const fillPoints = data.map((d, i) => pt(i, d.value)).map(([x, y]) => `${x},${y}`).join(' ');

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ overflow: 'visible' }}>
      {/* Grid */}
      {gridLevels.map((level, li) => (
        <polygon key={li}
          points={Array.from({ length: n }, (_, i) => {
            const a = angle(i);
            const rv = level * r;
            return `${cx + rv * Math.cos(a)},${cy + rv * Math.sin(a)}`;
          }).join(' ')}
          fill="none"
          stroke="var(--surface-3)"
          strokeWidth={1}
        />
      ))}
      {/* Axis lines */}
      {data.map((_, i) => {
        const a = angle(i);
        return <line key={i}
          x1={cx} y1={cy}
          x2={cx + r * Math.cos(a)} y2={cy + r * Math.sin(a)}
          stroke="var(--surface-3)" strokeWidth={1}
        />;
      })}
      {/* Fill */}
      <polygon
        points={fillPoints}
        fill="var(--accent-overlay-mid)"
        stroke="var(--accent)"
        strokeWidth={1.5}
        strokeLinejoin="round"
      />
      {/* Dots */}
      {data.map((d, i) => {
        const [x, y] = pt(i, d.value);
        return <circle key={i} cx={x} cy={y} r={3} fill="var(--accent)" />;
      })}
      {/* Labels */}
      {data.map((d, i) => {
        const [lx, ly] = labelPt(i);
        const anchor = lx < cx - 5 ? 'end' : lx > cx + 5 ? 'start' : 'middle';
        return (
          <text key={i} x={lx} y={ly}
            textAnchor={anchor} dominantBaseline="middle"
            fontSize={9} fontFamily="var(--font-body)" fontWeight={700}
            fill="var(--text-muted)" letterSpacing="0.08em"
            textTransform="uppercase"
            style={{ textTransform: 'uppercase' }}
          >{d.label.toUpperCase()}</text>
        );
      })}
    </svg>
  );
}

// ── Mini Sparkline ───────────────────────────────────────────────────────
function Sparkline({ data, width = 60, height = 24, color = 'var(--accent)' }) {
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / range) * height;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth={1.5} strokeLinejoin="round" />
    </svg>
  );
}

// ── Mini Line Chart ──────────────────────────────────────────────────────
function LineChart({ data, width = 320, height = 120, label }) {
  const maxV = Math.max(...data.map(d => d.value));
  const minV = Math.min(...data.map(d => d.value));
  const range = maxV - minV || 1;
  const pad = { t: 16, r: 12, b: 28, l: 32 };
  const W = width - pad.l - pad.r;
  const H = height - pad.t - pad.b;

  const pts = data.map((d, i) => {
    const x = pad.l + (i / (data.length - 1)) * W;
    const y = pad.t + H - ((d.value - minV) / range) * H;
    return { x, y, ...d };
  });
  const polyline = pts.map(p => `${p.x},${p.y}`).join(' ');
  const area = `${pts[0].x},${pad.t + H} ${polyline} ${pts[pts.length-1].x},${pad.t + H}`;

  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <defs>
        <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.18" />
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* Grid lines */}
      {[0, 0.25, 0.5, 0.75, 1].map((t, i) => {
        const y = pad.t + H - t * H;
        return (
          <g key={i}>
            <line x1={pad.l} y1={y} x2={pad.l + W} y2={y} stroke="var(--surface-2)" strokeWidth={1} />
            <text x={pad.l - 6} y={y + 4} fontSize={9} fill="var(--text-dim)" textAnchor="end" fontFamily="var(--font-mono)">
              {(minV + t * range).toFixed(1)}
            </text>
          </g>
        );
      })}
      {/* Area */}
      <polygon points={area} fill="url(#areaGrad)" />
      {/* Line */}
      <polyline points={polyline} fill="none" stroke="var(--accent)" strokeWidth={2} strokeLinejoin="round"
        filter="drop-shadow(0 0 4px var(--accent-glow))" />
      {/* X labels */}
      {pts.filter((_, i) => i % Math.ceil(data.length / 6) === 0).map((p, i) => (
        <text key={i} x={p.x} y={pad.t + H + 16} fontSize={9} fill="var(--text-dim)"
          textAnchor="middle" fontFamily="var(--font-mono)">{p.label}</text>
      ))}
      {/* Last dot */}
      <circle cx={pts[pts.length-1].x} cy={pts[pts.length-1].y} r={3} fill="var(--accent)" />
    </svg>
  );
}

// ── Phone Frame ──────────────────────────────────────────────────────────
function PhoneFrame({ children, width = 375, height = 812 }) {
  const scale = Math.min(1, 560 / height, 320 / width);
  return (
    <div style={{
      width: width * scale + 28, height: height * scale + 28,
      background: 'linear-gradient(160deg, #1E2631, #141A22)',
      borderRadius: 42, padding: 14,
      boxShadow: '0 40px 80px -20px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.07)',
      flexShrink: 0, position: 'relative'
    }}>
      {/* Dynamic island */}
      <div style={{
        position: 'absolute', top: 14 + 12, left: '50%', transform: 'translateX(-50%)',
        width: 96, height: 28, background: '#000', borderRadius: 20, zIndex: 10
      }} />
      {/* Screen */}
      <div style={{
        width: '100%', height: '100%',
        background: 'var(--bg)', borderRadius: 32,
        overflow: 'hidden', position: 'relative',
        transform: `scale(${scale})`, transformOrigin: 'top left',
        width: width, height: height,
      }}>
        {/* Status bar */}
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: 44,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '0 20px', zIndex: 5, pointerEvents: 'none'
        }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--text)' }}>9:41</span>
          <div style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
            <svg width="16" height="12" viewBox="0 0 16 12" fill="var(--text)"><rect x="0" y="4" width="3" height="8" rx="1"/><rect x="4" y="2" width="3" height="10" rx="1"/><rect x="8" y="0" width="3" height="12" rx="1"/><rect x="12" y="1" width="3" height="11" rx="1"/></svg>
            <svg width="16" height="12" viewBox="0 0 18 12" fill="var(--text)"><rect x="0" y="0" width="15" height="12" rx="2" fill="none" stroke="var(--text)" strokeWidth="1"/><rect x="1.5" y="1.5" width="9" height="9" rx="1"/><rect x="16" y="4" width="2" height="4" rx="1"/></svg>
          </div>
        </div>
        {children}
      </div>
      {/* Home indicator */}
      <div style={{
        position: 'absolute', bottom: 14 + 8, left: '50%', transform: 'translateX(-50%)',
        width: 110 * scale, height: 4, background: 'rgba(255,255,255,0.35)', borderRadius: 4
      }} />
    </div>
  );
}

// ── Card ─────────────────────────────────────────────────────────────────
function Card({ children, style, onClick, hover: hoverProp }) {
  const [hover, setHover] = React.useState(false);
  const isHoverable = onClick || hoverProp;
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => isHoverable && setHover(true)}
      onMouseLeave={() => isHoverable && setHover(false)}
      style={{
        background: 'var(--surface-1)',
        border: `1px solid ${hover ? 'var(--accent-deep)' : 'var(--border)'}`,
        borderRadius: 18,
        transition: 'transform 0.2s, border-color 0.2s',
        transform: hover && isHoverable ? 'translateY(-3px)' : 'none',
        cursor: onClick ? 'pointer' : 'default',
        ...style
      }}
    >{children}</div>
  );
}

// ── Section separator ─────────────────────────────────────────────────────
function Divider() {
  return <div style={{ height: 1, background: 'var(--border)', margin: '0' }} />;
}

// ── Avatar / Monogram ─────────────────────────────────────────────────────
function Avatar({ name, size = 32, src }) {
  const initials = name ? name.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase() : '?';
  const hue = name ? (name.charCodeAt(0) * 37 + name.charCodeAt(1 || 0) * 17) % 360 : 200;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: src ? 'transparent' : `oklch(0.45 0.12 ${hue})`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.35, fontWeight: 700, color: '#fff',
      flexShrink: 0, overflow: 'hidden',
      fontFamily: 'var(--font-display)',
    }}>
      {src ? <img src={src} width={size} height={size} style={{ objectFit: 'cover' }} /> : initials}
    </div>
  );
}

// Export all
Object.assign(window, {
  StreakChip, XPChip, EyebrowChip, LevelChip, StatusChip,
  BtnPrimary, BtnGhost,
  ProgressBar, RadarChart, Sparkline, LineChart,
  PhoneFrame, Card, Divider, Avatar,
});
