/**
 * 캔들 pane 좌측 하단 — 캔들 확대 보기 / 기본 보기 복원 버튼
 */
import React, { useState, useEffect, useCallback } from 'react';
import { ChartManager } from '../utils/ChartManager';

const IconExpand = () => (
  <svg width="13" height="13" viewBox="0 0 14 14" fill="none"
    stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="1,9 1,13 5,13"/>
    <line x1="1" y1="13" x2="5.5" y2="8.5"/>
    <polyline points="13,5 13,1 9,1"/>
    <line x1="13" y1="1" x2="8.5" y2="5.5"/>
  </svg>
);

const IconRestore = () => (
  <svg width="13" height="13" viewBox="0 0 14 14" fill="none"
    stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="5,13 1,13 1,9"/>
    <line x1="1" y1="13" x2="5.5" y2="8.5"/>
    <polyline points="9,1 13,1 13,5"/>
    <line x1="13" y1="1" x2="8.5" y2="5.5"/>
  </svg>
);

interface CandlePaneControlsProps {
  manager:     ChartManager;
  containerEl: HTMLElement;
  candleOnly:  boolean;
  onExpand:    () => void;
  onRestore:   () => void;
}

const CandlePaneControls: React.FC<CandlePaneControlsProps> = ({
  manager,
  containerEl,
  candleOnly,
  onExpand,
  onRestore,
}) => {
  const [pos, setPos] = useState<{ left: number; top: number } | null>(null);

  const updatePos = useCallback(() => {
    const main = manager.getPaneLayouts().find(l => l.paneIndex === 0);
    if (!main) { setPos(null); return; }
    const rect = containerEl.getBoundingClientRect();
    const paneBottomY = rect.top + main.topY + main.height;
    setPos({
      left: rect.left + 4,
      top:  paneBottomY - 30,
    });
  }, [manager, containerEl]);

  useEffect(() => {
    updatePos();
    const ro = new ResizeObserver(() => updatePos());
    ro.observe(containerEl);
    const id = setInterval(updatePos, 400);
    return () => { ro.disconnect(); clearInterval(id); };
  }, [containerEl, updatePos, candleOnly]);

  if (!pos) return null;

  return (
    <div
      className="candle-pane-controls"
      style={{ position: 'fixed', left: pos.left, top: pos.top, zIndex: 504 }}
      onMouseDown={e => e.stopPropagation()}
    >
      {candleOnly ? (
        <button
          type="button"
          className="pane-btn pane-btn-expand active"
          onClick={e => { e.stopPropagation(); onRestore(); }}
          title="기본 보기로 복원"
        >
          <IconRestore />
        </button>
      ) : (
        <button
          type="button"
          className="pane-btn pane-btn-expand"
          onClick={e => { e.stopPropagation(); onExpand(); }}
          title="캔들 전체보기 (캔들 영역 오버레이 지표 유지, 하단 보조지표 숨김)"
        >
          <IconExpand />
        </button>
      )}
    </div>
  );
};

export default CandlePaneControls;
