const { useState, useEffect, useRef } = React;

const BOOK_DEMO_LINK = "clearmetric/30min";
const BOOK_DEMO_URL = `https://cal.com/${BOOK_DEMO_LINK}`;
const BOOK_DEMO_CONFIG = {
  layout: "month_view",
  useSlotsViewOnSmallScreen: "true",
};

// Monospace section label
function Label({ num, children }) {
  return (
    <div className="mono-label">
      {num && <span className="num">{num}</span>}
      {children}
    </div>
  );
}

// Arrow icon
function Arrow({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none" className="arrow">
      <path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function SectionHead({ num, kicker, title, children, dark }) {
  return (
    <div className="sec-head">
      <Label num={num}>{kicker}</Label>
      <h2 style={{ marginTop: 20, color: dark ? '#fff' : undefined }}>{title}</h2>
      {children && <p style={{ color: dark ? '#B9BEC9' : undefined }}>{children}</p>}
    </div>
  );
}

// Small sparkline
function Spark({ values, color = 'var(--accent)', height = 40 }) {
  const w = 120, h = height;
  const max = Math.max(...values), min = Math.min(...values);
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
    return `${x},${y}`;
  }).join(' ');
  const areaPts = `0,${h} ${pts} ${w},${h}`;
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <polygon points={areaPts} fill={color} opacity="0.1"/>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
    </svg>
  );
}

function Bars({ values, color = 'var(--accent)', height = 60 }) {
  const max = Math.max(...values);
  return (
    <div style={{ display: 'flex', gap: 4, alignItems: 'flex-end', height }}>
      {values.map((v, i) => (
        <div key={i} style={{
          flex: 1, background: color, opacity: 0.25 + (v/max)*0.75,
          height: `${(v/max)*100}%`, borderRadius: '3px 3px 0 0', minHeight: 3,
        }}/>
      ))}
    </div>
  );
}

function openBookDemo(event) {
  if (event) {
    event.preventDefault();
    event.stopPropagation();
  }

  if (window.Cal?.ns?.["30min"]) {
    window.Cal.ns["30min"]("modal", {
      calLink: BOOK_DEMO_LINK,
      config: BOOK_DEMO_CONFIG,
    });
    return false;
  }

  window.open(BOOK_DEMO_URL, "_blank", "noopener,noreferrer");
  return false;
}

Object.assign(window, {
  Label,
  Arrow,
  SectionHead,
  Spark,
  Bars,
  openBookDemo,
  BOOK_DEMO_LINK,
  BOOK_DEMO_URL,
  BOOK_DEMO_CONFIG,
});
