const FSContext = React.createContext(null);

// Shared pointer-drag helper for intra-panel splitters
window.createPointerDragHandler = function (onStart, axis = 'row') {
  return (e) => {
    e.preventDefault();
    const start = axis === 'col' ? e.clientX : e.clientY;
    const ctx = onStart();
    const cls = axis === 'col' ? 'col-resizing' : 'row-resizing';
    document.body.classList.add(cls);
    const target = e.currentTarget;
    target.classList.add('active');
    const onMove = (ev) => {
      const delta = (axis === 'col' ? ev.clientX : ev.clientY) - start;
      ctx.onMove(delta);
    };
    const onUp = () => {
      document.body.classList.remove(cls);
      target.classList.remove('active');
      window.removeEventListener('pointermove', onMove);
      window.removeEventListener('pointerup', onUp);
    };
    window.addEventListener('pointermove', onMove);
    window.addEventListener('pointerup', onUp);
  };
};

function App() {
  const [sizes, setSizes] = React.useState({ colConti: 460, colScript: 620, rowTop: 560 });
  const [fs, setFs] = React.useState(null);

  const startCol = (key) =>
    window.createPointerDragHandler(() => {
      const startVal = sizes[key];
      return {
        onMove: (d) =>
          setSizes((s) => ({ ...s, [key]: Math.max(300, Math.min(1000, startVal + d)) })),
      };
    }, 'col');

  const startRow = () =>
    window.createPointerDragHandler(() => {
      const startVal = sizes.rowTop;
      return {
        onMove: (d) =>
          setSizes((s) => ({
            ...s,
            rowTop: Math.max(160, Math.min(window.innerHeight - 360, startVal + d)),
          })),
      };
    }, 'row');

  const colsStyle = {
    '--col-conti': sizes.colConti + 'px',
    '--col-script': sizes.colScript + 'px',
    '--row-top': sizes.rowTop + 'px',
  };

  const toggleFs = (k) => setFs((prev) => (prev === k ? null : k));

  return (
    <FSContext.Provider value={{ fs, toggleFs }}>
      <div className="app">
        <Header />
        <main className="main">
          <div className="cols" style={colsStyle}>
            <Continuity />
            <ScriptViewer />
            <Schedule />
            <TakesBoard />
            {/* V-handle 1: 스토리보드 뷰어 ↔ 대본뷰어 — full height */}
            <span
              className="resize v"
              style={{ left: `calc(${sizes.colConti}px + 7px)` }}
              onPointerDown={startCol('colConti')}
              title="크기 조정"
            />
            {/* V-handle 2: 대본뷰어 ↔ 제작일정 / takes-card column split */}
            <span
              className="resize v"
              style={{ left: `calc(${sizes.colConti}px + ${sizes.colScript}px + 21px)` }}
              onPointerDown={startCol('colScript')}
              title="크기 조정"
            />
            {/* H-handle: top row ↔ takes-card (대본뷰어/제작일정 ↕ 스크립트) */}
            <span
              className="resize h"
              style={{
                top: `calc(${sizes.rowTop}px + 7px)`,
                left: `calc(${sizes.colConti}px + 14px)`,
              }}
              onPointerDown={startRow()}
              title="크기 조정"
            />
          </div>
          <div className="foot">
            <span>© 2025 Ready-Action. All rights reserved. Powered by Dountt AI.</span>
            <span style={{ display: 'flex', gap: 12 }}>
              <span>v3.2.0</span>
              <span>· 마지막 동기화 14:32</span>
            </span>
          </div>
        </main>
        {fs && <div className="fs-backdrop" onClick={() => setFs(null)} />}
        <div className="fab-new">
          <span className="l">NEW</span>
          <span className="ct">2</span>
        </div>
      </div>
    </FSContext.Provider>
  );
}

// Reusable vertical splitter (drag horizontally to resize top section)
function VSplit({ initial = 300, min = 120, max = 900, children }) {
  const [h, setH] = React.useState(initial);
  const onDown = window.createPointerDragHandler(() => {
    const startVal = h;
    return { onMove: (d) => setH(Math.max(min, Math.min(max, startVal + d))) };
  }, 'row');
  const [top, bot] = React.Children.toArray(children);
  return (
    <div className="vsplit">
      <div className="vsplit-top" style={{ height: h }}>
        {top}
      </div>
      <span className="resize h inline" onPointerDown={onDown} title="크기 조정" />
      <div className="vsplit-bot">{bot}</div>
    </div>
  );
}
window.VSplit = VSplit;

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
