// Measure overlay — Figma-like inspector for the live design
// Shortcuts: M = toggle measure, G = toggle 8px grid, R = toggle rulers, Esc = close
const MeasureOverlay = () => {
  const [on, setOn] = React.useState(false);
  const [grid, setGrid] = React.useState(false);
  const [rulers, setRulers] = React.useState(true);
  const [hover, setHover] = React.useState(null); // {rect, tag, cls}
  const [pinned, setPinned] = React.useState(null); // pinned element rect for distance measure
  const [mouse, setMouse] = React.useState({x:0,y:0});

  // Keyboard shortcuts
  React.useEffect(()=>{
    const h = (e) => {
      if (e.target.matches('input, textarea')) return;
      if (e.key === 'm' || e.key === 'M') setOn(v=>!v);
      if (e.key === 'g' || e.key === 'G') setGrid(v=>!v);
      if (e.key === 'r' || e.key === 'R') setRulers(v=>!v);
      if (e.key === 'Escape') { setOn(false); setPinned(null); }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  // Track hover element + mouse
  React.useEffect(()=>{
    if (!on) { setHover(null); return; }
    const move = (e) => {
      setMouse({x:e.clientX, y:e.clientY});
      // Skip the overlay itself
      const els = document.elementsFromPoint(e.clientX, e.clientY)
        .filter(el => !el.closest('[data-measure-ui]'));
      const el = els[0];
      if (!el) { setHover(null); return; }
      const rect = el.getBoundingClientRect();
      const cs = getComputedStyle(el);
      setHover({
        rect,
        tag: el.tagName.toLowerCase(),
        cls: (el.className && typeof el.className === 'string') ? el.className.split(' ').filter(Boolean).slice(0,2).join('.') : '',
        padding: `${parseInt(cs.paddingTop)} ${parseInt(cs.paddingRight)} ${parseInt(cs.paddingBottom)} ${parseInt(cs.paddingLeft)}`,
        font: cs.fontSize + ' / ' + (cs.fontWeight),
        color: cs.color,
        bg: cs.backgroundColor,
      });
    };
    const click = (e) => {
      if (e.target.closest('[data-measure-ui]')) return;
      e.preventDefault(); e.stopPropagation();
      const els = document.elementsFromPoint(e.clientX, e.clientY)
        .filter(el => !el.closest('[data-measure-ui]'));
      const el = els[0];
      if (!el) return;
      const rect = el.getBoundingClientRect();
      setPinned(prev => prev && prev.el === el ? null : { el, rect });
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('click', click, true);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('click', click, true);
    };
  }, [on]);

  // Floating toggle (always visible)
  const toggleBtn = (
    <div data-measure-ui style={{
      position:'fixed', top:12, right:12, zIndex:99999,
      display:'flex', gap:4, padding:4,
      background:'#0a0a0a', border:'1px solid #262626',
      borderRadius:8, boxShadow:'0 4px 12px rgba(0,0,0,.25)',
      fontFamily:'ui-sans-serif, system-ui'
    }}>
      <button onClick={()=>setOn(v=>!v)} title="Measure (M)" style={btnStyle(on)}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 6H3v12h18V6z"/><path d="M7 6v4M11 6v6M15 6v4M19 6v6"/></svg>
      </button>
      <button onClick={()=>setGrid(v=>!v)} title="Grid 8px (G)" style={btnStyle(grid)}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
      </button>
      <button onClick={()=>setRulers(v=>!v)} title="Rulers (R)" style={btnStyle(rulers && on)}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 3h18v6H3zM3 9v12h6V9"/></svg>
      </button>
    </div>
  );

  if (!on) {
    return <>{toggleBtn}{grid && <Grid/>}</>;
  }

  return (
    <>
      {toggleBtn}
      {grid && <Grid/>}
      {rulers && <Rulers mouse={mouse}/>}
      {hover && <HoverBox info={hover}/>}
      {pinned && hover && pinned.el !== hover.el && <DistanceLines a={pinned.rect} b={hover.rect}/>}
      {pinned && <PinnedBox rect={pinned.rect}/>}
      <Help/>
    </>
  );
};

const btnStyle = (active) => ({
  display:'flex', alignItems:'center', justifyContent:'center',
  width:28, height:28, padding:0, border:'none',
  background: active ? '#fafafa' : 'transparent',
  color: active ? '#0a0a0a' : '#a1a1aa',
  borderRadius:5, cursor:'pointer'
});

const Grid = () => (
  <div data-measure-ui style={{
    position:'fixed', inset:0, zIndex:99990, pointerEvents:'none',
    backgroundImage:'linear-gradient(to right, rgba(124,58,237,.08) 1px, transparent 1px), linear-gradient(to bottom, rgba(124,58,237,.08) 1px, transparent 1px)',
    backgroundSize:'8px 8px',
  }}/>
);

const Rulers = ({ mouse }) => (
  <>
    <div data-measure-ui style={{position:'fixed', top:0, left:0, right:0, height:20, background:'#0a0a0acc', backdropFilter:'blur(4px)', borderBottom:'1px solid #262626', zIndex:99991, pointerEvents:'none', display:'flex', alignItems:'flex-end', color:'#a1a1aa', fontSize:9, fontFamily:'ui-monospace,monospace'}}>
      {Array.from({length:50}).map((_,i)=>(
        <div key={i} style={{width:50, position:'relative', flexShrink:0, height:'100%'}}>
          <div style={{position:'absolute', bottom:0, left:0, width:1, height:6, background:'#525252'}}/>
          <span style={{position:'absolute', bottom:7, left:2}}>{i*50}</span>
        </div>
      ))}
      {/* mouse marker */}
      <div style={{position:'fixed', top:0, left:mouse.x, width:1, height:20, background:'#7c3aed'}}/>
      <div style={{position:'fixed', top:2, left:mouse.x+4, padding:'0 4px', background:'#7c3aed', color:'#fff', fontSize:10, borderRadius:2, fontFamily:'ui-monospace,monospace'}}>{mouse.x}</div>
    </div>
    <div data-measure-ui style={{position:'fixed', top:20, left:0, bottom:0, width:20, background:'#0a0a0acc', backdropFilter:'blur(4px)', borderRight:'1px solid #262626', zIndex:99991, pointerEvents:'none'}}>
      {Array.from({length:50}).map((_,i)=>(
        <div key={i} style={{height:50, position:'relative', width:'100%'}}>
          <div style={{position:'absolute', top:0, right:0, height:1, width:6, background:'#525252'}}/>
          <span style={{position:'absolute', top:2, right:7, color:'#a1a1aa', fontSize:9, fontFamily:'ui-monospace,monospace', writingMode:'vertical-rl'}}>{i*50}</span>
        </div>
      ))}
      <div style={{position:'fixed', left:0, top:mouse.y, width:20, height:1, background:'#7c3aed'}}/>
      <div style={{position:'fixed', left:2, top:mouse.y+4, padding:'0 4px', background:'#7c3aed', color:'#fff', fontSize:10, borderRadius:2, fontFamily:'ui-monospace,monospace'}}>{mouse.y}</div>
    </div>
  </>
);

const HoverBox = ({ info }) => {
  const r = info.rect;
  const labelW = `${Math.round(r.width)} × ${Math.round(r.height)}`;
  return (
    <>
      <div data-measure-ui style={{
        position:'fixed', top:r.top, left:r.left, width:r.width, height:r.height,
        border:'1px solid #7c3aed', background:'rgba(124,58,237,.08)',
        zIndex:99992, pointerEvents:'none'
      }}/>
      {/* size badge */}
      <div data-measure-ui style={{
        position:'fixed', top:r.bottom + 2, left:r.left,
        padding:'2px 6px', background:'#7c3aed', color:'#fff',
        fontSize:11, fontFamily:'ui-monospace,monospace', fontWeight:600,
        borderRadius:3, zIndex:99993, pointerEvents:'none', whiteSpace:'nowrap'
      }}>{labelW}</div>
      {/* tag info card */}
      <div data-measure-ui style={{
        position:'fixed',
        top: r.bottom + 24 > window.innerHeight - 120 ? r.top - 110 : r.bottom + 24,
        left: Math.min(r.left, window.innerWidth - 240),
        width:230, padding:'8px 10px',
        background:'#0a0a0a', color:'#fafafa', border:'1px solid #262626', borderRadius:6,
        fontSize:11, fontFamily:'ui-monospace,monospace', lineHeight:1.5,
        zIndex:99993, pointerEvents:'none', boxShadow:'0 4px 12px rgba(0,0,0,.4)'
      }}>
        <div style={{color:'#7c3aed', fontWeight:700, marginBottom:4}}>{info.tag}{info.cls && '.'+info.cls}</div>
        <div><span style={{color:'#71717a'}}>size</span> {labelW}</div>
        <div><span style={{color:'#71717a'}}>pad</span> {info.padding}</div>
        <div><span style={{color:'#71717a'}}>font</span> {info.font}</div>
        <div className="row" style={{display:'flex',gap:4,alignItems:'center'}}>
          <span style={{color:'#71717a'}}>color</span>
          <span style={{display:'inline-block',width:10,height:10,background:info.color,borderRadius:2,border:'1px solid #262626'}}/>
          {info.color}
        </div>
      </div>
    </>
  );
};

const PinnedBox = ({ rect }) => (
  <div data-measure-ui style={{
    position:'fixed', top:rect.top, left:rect.left, width:rect.width, height:rect.height,
    border:'2px solid #ec4899', background:'rgba(236,72,153,.08)',
    zIndex:99991, pointerEvents:'none'
  }}/>
);

const DistanceLines = ({ a, b }) => {
  // Compute gaps between two rectangles
  const gapX = b.left > a.right ? b.left - a.right
             : a.left > b.right ? a.left - b.right
             : 0;
  const gapY = b.top > a.bottom ? b.top - a.bottom
             : a.top > b.bottom ? a.top - b.bottom
             : 0;
  // Horizontal line
  const hLine = gapX > 0 ? (() => {
    const x1 = b.left > a.right ? a.right : b.right;
    const x2 = b.left > a.right ? b.left : a.left;
    const y = (Math.max(a.top,b.top) + Math.min(a.bottom,b.bottom))/2;
    return { x1, x2, y };
  })() : null;
  const vLine = gapY > 0 ? (() => {
    const y1 = b.top > a.bottom ? a.bottom : b.bottom;
    const y2 = b.top > a.bottom ? b.top : a.top;
    const x = (Math.max(a.left,b.left) + Math.min(a.right,b.right))/2;
    return { y1, y2, x };
  })() : null;
  return (
    <>
      {hLine && (
        <>
          <div data-measure-ui style={{position:'fixed', top:hLine.y, left:hLine.x1, width:hLine.x2-hLine.x1, height:1, background:'#ec4899', zIndex:99992, pointerEvents:'none'}}/>
          <div data-measure-ui style={{position:'fixed', top:hLine.y - 10, left:(hLine.x1+hLine.x2)/2 - 18, padding:'1px 5px', background:'#ec4899', color:'#fff', fontSize:10, fontFamily:'ui-monospace,monospace', fontWeight:600, borderRadius:2, zIndex:99993, pointerEvents:'none'}}>{Math.round(gapX)}px</div>
        </>
      )}
      {vLine && (
        <>
          <div data-measure-ui style={{position:'fixed', left:vLine.x, top:vLine.y1, height:vLine.y2-vLine.y1, width:1, background:'#ec4899', zIndex:99992, pointerEvents:'none'}}/>
          <div data-measure-ui style={{position:'fixed', left:vLine.x + 4, top:(vLine.y1+vLine.y2)/2 - 7, padding:'1px 5px', background:'#ec4899', color:'#fff', fontSize:10, fontFamily:'ui-monospace,monospace', fontWeight:600, borderRadius:2, zIndex:99993, pointerEvents:'none'}}>{Math.round(gapY)}px</div>
        </>
      )}
    </>
  );
};

const Help = () => (
  <div data-measure-ui style={{
    position:'fixed', bottom:60, right:12, zIndex:99994,
    padding:'8px 12px', background:'#0a0a0a', color:'#a1a1aa',
    border:'1px solid #262626', borderRadius:6,
    fontSize:11, fontFamily:'ui-monospace,monospace', lineHeight:1.7
  }}>
    <div><kbd style={kbd}>M</kbd> measure</div>
    <div><kbd style={kbd}>G</kbd> 8px grid</div>
    <div><kbd style={kbd}>R</kbd> rulers</div>
    <div><kbd style={kbd}>click</kbd> pin element</div>
    <div><kbd style={kbd}>Esc</kbd> close</div>
  </div>
);

const kbd = {
  display:'inline-block', minWidth:14, padding:'1px 4px',
  background:'#1a1a1a', color:'#fafafa', border:'1px solid #262626',
  borderRadius:3, fontSize:10, marginRight:6, textAlign:'center'
};

window.MeasureOverlay = MeasureOverlay;
