/* Flow-OS shared visual primitives */
const { useMemo } = React;

// =============================================================
// FlowGauge — semicircle tick gauge (semáforo: red→amber→green)
// =============================================================
function FlowGauge({ value = 74, size = 280, label = "FLOW SCORE", showDelta = null, range = [0, 100] }) {
  const cx = size / 2;
  const cy = size * 0.62;
  const r = size * 0.42;
  const ticks = 80;
  const startAngle = 180; // left
  const endAngle = 360;   // right (180° sweep top arc)
  const valuePct = (value - range[0]) / (range[1] - range[0]);

  // semáforo color stops
  const colorAt = (t) => {
    // t: 0..1 across the arc
    if (t < 0.4) {
      // red → amber
      const k = t / 0.4;
      return mix("#e1473d", "#e8b53a", k);
    } else if (t < 0.7) {
      const k = (t - 0.4) / 0.3;
      return mix("#e8b53a", "#4fd693", k);
    } else {
      const k = (t - 0.7) / 0.3;
      return mix("#4fd693", "#2ea66a", k);
    }
  };

  function mix(a, b, t) {
    const ah = a.replace('#', ''); const bh = b.replace('#', '');
    const ar = parseInt(ah.slice(0, 2), 16), ag = parseInt(ah.slice(2, 4), 16), ab = parseInt(ah.slice(4, 6), 16);
    const br = parseInt(bh.slice(0, 2), 16), bg = parseInt(bh.slice(2, 4), 16), bb = parseInt(bh.slice(4, 6), 16);
    const r = Math.round(ar + (br - ar) * t);
    const g = Math.round(ag + (bg - ag) * t);
    const bl = Math.round(ab + (bb - ab) * t);
    return `rgb(${r},${g},${bl})`;
  }

  const tickElements = [];
  for (let i = 0; i < ticks; i++) {
    const t = i / (ticks - 1);
    const angle = startAngle + (endAngle - startAngle) * t;
    const rad = (angle * Math.PI) / 180;
    const isActive = t <= valuePct + 0.001;
    const color = isActive ? colorAt(t) : 'rgba(0,0,0,0.08)';
    const innerR = r - (isActive ? 18 : 14);
    const outerR = r;
    const x1 = cx + Math.cos(rad) * innerR;
    const y1 = cy + Math.sin(rad) * innerR;
    const x2 = cx + Math.cos(rad) * outerR;
    const y2 = cy + Math.sin(rad) * outerR;
    tickElements.push(
      <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={color} strokeWidth={2} strokeLinecap="round" />
    );
  }

  // Pointer position
  const ptAngle = startAngle + (endAngle - startAngle) * valuePct;
  const ptRad = (ptAngle * Math.PI) / 180;
  const ptX = cx + Math.cos(ptRad) * (r + 8);
  const ptY = cy + Math.sin(ptRad) * (r + 8);

  return (
    <div style={{ position: 'relative', width: size, height: size * 0.78 }}>
      <svg className="gauge-svg" width={size} height={size * 0.78} viewBox={`0 0 ${size} ${size * 0.78}`}>
        {/* range labels */}
        <text x={cx + Math.cos((180 * Math.PI) / 180) * (r + 14)} y={cy + 4} fontSize="11" fill="var(--ink-3)" fontFamily="var(--mono)" textAnchor="end">{range[0]}</text>
        <text x={cx + Math.cos((360 * Math.PI) / 180) * (r + 14)} y={cy + 4} fontSize="11" fill="var(--ink-3)" fontFamily="var(--mono)" textAnchor="start">{range[1]}</text>
        {/* tick marks */}
        {tickElements}
        {/* threshold labels */}
        <text x={cx + Math.cos(((180 + 0.4 * 180) * Math.PI) / 180) * (r + 14)} y={cy + Math.sin(((180 + 0.4 * 180) * Math.PI) / 180) * (r + 14)} fontSize="10" fill="var(--ink-4)" fontFamily="var(--mono)" textAnchor="middle">40</text>
        <text x={cx + Math.cos(((180 + 0.7 * 180) * Math.PI) / 180) * (r + 14)} y={cy + Math.sin(((180 + 0.7 * 180) * Math.PI) / 180) * (r + 14)} fontSize="10" fill="var(--ink-4)" fontFamily="var(--mono)" textAnchor="middle">70</text>
      </svg>
      <div style={{
        position: 'absolute',
        top: '50%',
        left: 0,
        right: 0,
        textAlign: 'center',
        transform: 'translateY(-10%)',
        pointerEvents: 'none'
      }}>
        <div style={{ fontFamily: 'var(--serif)', fontSize: size * 0.28, lineHeight: 1, color: 'var(--ink)' }}>{value}</div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', marginTop: 6 }}>{label}</div>
      </div>
      {showDelta !== null && (
        <div style={{
          position: 'absolute',
          left: ptX - 22,
          top: ptY - 12,
          background: 'var(--ink)',
          color: '#fff',
          fontFamily: 'var(--mono)',
          fontSize: 10,
          padding: '3px 7px',
          borderRadius: 999,
          display: 'flex',
          alignItems: 'center',
          gap: 4
        }}>
          <span style={{ color: showDelta > 0 ? 'var(--green-bright)' : 'var(--red)' }}>{showDelta > 0 ? '▲' : '▼'}</span>
          {Math.abs(showDelta)} pts
        </div>
      )}
    </div>
  );
}

// =============================================================
// MiniSpark — small line/area trend
// =============================================================
function MiniSpark({ data, width = 200, height = 60, color = "var(--ink)", fill = false, dashed = false }) {
  const max = Math.max(...data);
  const 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 * 0.85 - height * 0.1;
    return [x, y];
  });
  const path = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0]} ${p[1]}`).join(' ');
  const areaPath = `${path} L ${width} ${height} L 0 ${height} Z`;

  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      {fill && <path d={areaPath} fill={color} opacity={0.12} />}
      <path d={path} fill="none" stroke={color} strokeWidth={1.5} strokeDasharray={dashed ? "3 3" : "0"} strokeLinecap="round" strokeLinejoin="round" />
      {pts.map((p, i) => (i === pts.length - 1) && (
        <circle key={i} cx={p[0]} cy={p[1]} r={3} fill={color} />
      ))}
    </svg>
  );
}

// =============================================================
// HRV bars — tick-style bar chart
// =============================================================
function TickBars({ data, width = 280, height = 80, accent = "var(--green)", baselineIdx = -1, responsive = false, colorByValue = false }) {
  const max = Math.max(...data);
  const tickW = 3;
  const gap = (width - data.length * tickW) / (data.length - 1);

  const svgProps = responsive
    ? { width: "100%", height, viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: "none", style: { display: 'block', maxWidth: '100%' } }
    : { width, height, viewBox: `0 0 ${width} ${height}` };

  // Color ramp red→amber→green→purple based on normalized value (0..1)
  const colorFor = (v) => {
    const t = Math.max(0, Math.min(1, v / max));
    if (t < 0.30) return 'var(--red)';
    if (t < 0.50) return '#e07a5f';        // red-orange
    if (t < 0.65) return 'var(--amber)';
    if (t < 0.78) return '#c9a23a';        // amber-olive
    if (t < 0.88) return 'var(--green)';
    if (t < 0.96) return '#3fa86b';        // deep green
    return '#7c5fd1';                      // flow purple
  };

  return (
    <svg {...svgProps}>
      {data.map((v, i) => {
        const h = (v / max) * height * 0.85;
        const x = i * (tickW + gap);
        const y = height - h;
        const isAccent = i === baselineIdx;
        const fill = colorByValue ? colorFor(v) : (isAccent ? accent : 'rgba(15,15,14,0.6)');
        return <rect key={i} x={x} y={y} width={tickW} height={h} rx={1.5} fill={fill} />;
      })}
    </svg>
  );
}

// =============================================================
// HeatCell color helper
// =============================================================
// Pass `flow=true` to enable the purple "in flow" tier above 85.
// We keep the purple value here so it's consistent across the app.
const FLOW_PURPLE = '#7c5fd1';
const FLOW_PURPLE_SOFT = 'rgba(124,95,209,0.16)';

function statusColor(value, flow) {
  if (flow && value >= 85) return { bg: FLOW_PURPLE, soft: FLOW_PURPLE_SOFT, text: FLOW_PURPLE };
  if (value >= 70) return { bg: 'var(--green)', soft: 'var(--green-soft)', text: 'var(--green)' };
  if (value >= 55) return { bg: 'var(--amber)', soft: 'var(--amber-soft)', text: 'var(--amber)' };
  return { bg: 'var(--red)', soft: 'var(--red-soft)', text: 'var(--red)' };
}

function StatusDot({ value, size = 8 }) {
  const c = statusColor(value);
  return <span className="dot" style={{ width: size, height: size, background: c.bg }}></span>;
}

// =============================================================
// Logo
// =============================================================
function FlowLogo({ size = 18 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="11" stroke="var(--ink)" strokeWidth="1.2" />
        <path d="M5 14 Q 9 8, 12 12 T 19 10" stroke="var(--ink)" strokeWidth="1.5" fill="none" strokeLinecap="round" />
        <circle cx="19" cy="10" r="2" fill="var(--green)" />
      </svg>
      <span style={{ fontFamily: 'var(--serif)', fontSize: size + 2, lineHeight: 1, letterSpacing: '-0.01em' }}>Flow<span style={{ color: 'var(--ink-3)' }}>·</span>OS</span>
    </div>
  );
}

Object.assign(window, { FlowGauge, MiniSpark, TickBars, statusColor, StatusDot, FlowLogo, FLOW_PURPLE, FLOW_PURPLE_SOFT });
