// Canvas BI panel — drop metric chips onto canvas, tiles render based on data shape
function CanvasPanel() {
  const [tiles, setTiles] = React.useState([]);
  const [dragging, setDragging] = React.useState(null);
  const canvasRef = React.useRef(null);

  const metrics = [
    { id: 'mrr', name: 'MRR', type: 'metric', kind: 'value' },
    { id: 'nrr', name: 'NRR (TTM)', type: 'metric', kind: 'value' },
    { id: 'new_customers', name: 'New Customers', type: 'metric', kind: 'trend' },
    { id: 'churn', name: 'Churn Rate', type: 'metric', kind: 'bars' },
    { id: 'active', name: 'Active Customers', type: 'segment', kind: 'value' },
    { id: 'region', name: 'Region', type: 'dim', kind: 'bars' },
  ];

  const tileSpecs = {
    mrr: { label: 'Monthly Recurring Revenue', value: '$4.82M', trend: '+8.2%', chart: [3.1, 3.4, 3.6, 3.9, 4.1, 4.3, 4.5, 4.82], kind: 'spark' },
    nrr: { label: 'Net Revenue Retention · TTM', value: '118%', trend: '+3.1 pts', chart: [108, 110, 112, 113, 115, 116, 117, 118], kind: 'spark' },
    new_customers: { label: 'New Customers · Jan–Aug', value: '', trend: '', chart: [120, 155, 180, 210, 195, 230, 260, 280], kind: 'spark' },
    churn: { label: 'Churn by Cohort', value: '', trend: '', chart: [2.1, 1.8, 2.3, 1.9, 1.5, 1.3, 1.4, 1.1], kind: 'bars' },
    active: { label: 'Active Customers', value: '2,847', trend: '+142 this month', chart: [2.6, 2.65, 2.7, 2.75, 2.79, 2.82, 2.84, 2.85], kind: 'spark' },
    region: { label: 'Customers by Region', value: '', trend: '', chart: [840, 620, 480, 510, 397], kind: 'bars' },
  };

  const onDragStart = (m, e) => {
    e.dataTransfer.setData('text/plain', m.id);
    e.dataTransfer.effectAllowed = 'copy';
    setDragging(m.id);
  };
  const onDragEnd = () => setDragging(null);

  const onDrop = (e) => {
    e.preventDefault();
    const id = e.dataTransfer.getData('text/plain');
    const rect = canvasRef.current.getBoundingClientRect();
    const x = Math.max(16, Math.min(rect.width - 240, e.clientX - rect.left - 120));
    const y = Math.max(16, Math.min(rect.height - 120, e.clientY - rect.top - 40));
    if (!tiles.find(t => t.id === id)) {
      setTiles([...tiles, { id, x, y }]);
    }
  };
  const onDragOver = (e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; };

  const autoDemo = () => {
    setTiles([]);
    const sample = ['mrr', 'new_customers', 'churn'];
    sample.forEach((id, i) => {
      setTimeout(() => {
        setTiles(prev => [...prev, {
          id,
          x: [24, 230, 24][i],
          y: [20, 20, 160][i],
        }]);
      }, 350 * (i + 1));
    });
  };

  React.useEffect(() => {
    const t = setTimeout(autoDemo, 600);
    return () => clearTimeout(t);
  }, []);

  return (
    <React.Fragment>
      <div className="platform-copy">
        <h2>Governed exploration, without another dashboard.</h2>
        <p className="lede">Drop an approved definition onto the canvas. Clearmetric runs it against live data using the governed bindings — so analysts explore the real numbers, starting from the same business meaning every time.</p>
        <ul className="bullets">
          <li>Start from approved definitions — not raw SQL or chart config.</li>
          <li>Live data, rendered through the governed contract.</li>
          <li>Slice with segments, compare across dimensions, follow up in seconds.</li>
        </ul>
        <div style={{ marginTop: 28 }}>
          <button className="btn btn--ghost btn--sm" onClick={() => { setTiles([]); setTimeout(autoDemo, 100); }}>↻ Replay demo</button>
          <button className="btn btn--ghost btn--sm" onClick={() => setTiles([])} style={{ marginLeft: 8 }}>Clear canvas</button>
        </div>
      </div>
      <div className="canvas-mock">
        <div className="cm-chrome">
          <div className="cm-dots"><span/><span/><span/></div>
          <div className="cm-title">canvas · Board review · governed</div>
        </div>
        <div className="cm-body">
          <div className="cm-side">
            <div className="cm-search">🔍 Search governed metrics…</div>
            <div className="cm-group">Metrics</div>
            {metrics.filter(m => m.type === 'metric').map(m => (
              <div
                key={m.id}
                className="cm-metric"
                draggable
                onDragStart={(e) => onDragStart(m, e)}
                onDragEnd={onDragEnd}
              >
                <span className="tag m">M</span>{m.name}
              </div>
            ))}
            <div className="cm-group">Segments & dims</div>
            {metrics.filter(m => m.type !== 'metric').map(m => (
              <div
                key={m.id}
                className="cm-metric"
                draggable
                onDragStart={(e) => onDragStart(m, e)}
                onDragEnd={onDragEnd}
              >
                <span className="tag d">{m.type === 'segment' ? 'S' : 'D'}</span>{m.name}
              </div>
            ))}
          </div>
          <div className="cm-canvas" ref={canvasRef} onDrop={onDrop} onDragOver={onDragOver}>
            <div className={"cm-empty " + (tiles.length ? 'hide' : '')}>
              <div className="arrow">↙</div>
              <div>Drag a metric onto the canvas</div>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)' }}>GOVERNED · AUTO-RENDERED</div>
            </div>
            {tiles.map((t, i) => {
              const spec = tileSpecs[t.id];
              const isBars = spec.kind === 'bars';
              return (
                <div key={t.id} className="cm-tile" style={{ left: t.x, top: t.y, width: 200, height: 132 }}>
                  <div className="cm-tile__label">{spec.label}</div>
                  {spec.value && <div className="cm-tile__val">{spec.value}</div>}
                  {spec.trend && <div className="cm-tile__trend">↑ {spec.trend}</div>}
                  <div className="cm-tile__chart" style={{ marginTop: spec.value ? 4 : 12, height: spec.value ? 38 : 74 }}>
                    {isBars
                      ? <Bars values={spec.chart} height={spec.value ? 38 : 74}/>
                      : <Spark values={spec.chart} height={spec.value ? 38 : 74}/>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

window.CanvasPanel = CanvasPanel;
