/* global React, ReactDOM, SUMMIT, Sidebar, TopBar, ProcessMap, DetailDrawer */

const appCss = {
  header: { flexShrink: 0, background: '#fff', borderBottom: '1px solid #eef1f2', padding: '16px 26px 14px' },
  row: { display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' },
  kicker: { fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#1f9c69', margin: 0 },
  title: { fontFamily: "'Poppins', sans-serif", fontSize: 19, fontWeight: 700, color: '#04454c', letterSpacing: '-0.02em', margin: '2px 0 0' },
  seg: { display: 'inline-flex', background: '#f3f5f6', borderRadius: 999, padding: 3, gap: 2 },
  segBtn: { border: 0, background: 'transparent', borderRadius: 999, padding: '7px 15px', fontSize: 12.5, fontWeight: 600, color: '#6b7273', cursor: 'pointer', fontFamily: 'inherit', transition: 'all 160ms cubic-bezier(0.2,0.7,0.2,1)', whiteSpace: 'nowrap' },
  segBtnActive: { background: '#fff', color: '#04454c', boxShadow: '0 1px 3px rgba(4,69,76,0.12)' },
  zoom: { display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 'auto' },
  zoomBtn: { width: 30, height: 30, borderRadius: 8, border: '1px solid #e6e9eb', background: '#fff', color: '#04454c', cursor: 'pointer', fontSize: 15, fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center' },
  zoomVal: { fontSize: 12, fontWeight: 600, color: '#6b7273', width: 56, textAlign: 'center' },
  legend: { display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginTop: 13 },
  legItem: { display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5, color: '#6b7273', fontWeight: 500 },
  stage: { position: 'relative', flex: 1, minHeight: 0, overflow: 'hidden', background: '#f6f8f9' },
  scroll: { position: 'absolute', inset: 0, overflow: 'auto' },
};

function ZoomBtn({ children, onClick, title }) {
  return <button style={appCss.zoomBtn} onClick={onClick} title={title} type="button">{children}</button>;
}

function Legend({ roles }) {
  return (
    <div style={appCss.legend}>
      {SUMMIT.LANE_ORDER.map((k) => (
        <span key={k} style={appCss.legItem}>
          <span style={{ width: 10, height: 10, borderRadius: 999, background: roles[k].bar }} />
          {roles[k].name.split(' ')[0]} · {roles[k].title.split(' ')[0] === 'Office' ? 'Coordinator' : (roles[k].title.split(' ')[0])}
        </span>
      ))}
      <span style={{ width: 1, height: 16, background: '#e6e9eb' }} />
      <span style={appCss.legItem}>
        <span style={{ width: 11, height: 11, background: '#65ecac', transform: 'rotate(45deg)', borderRadius: 2, display: 'inline-block' }} /> Decision
      </span>
      <span style={appCss.legItem}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2, background: '#04454c', borderRadius: 999, padding: '3px 7px' }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: '#aaa' }} />
          <span style={{ color: '#65ecac', fontSize: 8 }}>→</span>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: '#65ecac' }} />
        </span>
        Handoff between roles
      </span>
    </div>
  );
}

function App() {
  const roles = SUMMIT.ROLES;
  const [viewKey, setViewKey] = React.useState('lifecycle');
  const [selectedId, setSelectedId] = React.useState(null);
  const [zoom, setZoom] = React.useState(1);
  const [autoFit, setAutoFit] = React.useState(true);
  const stageRef = React.useRef(null);
  const view = SUMMIT.views[viewKey];

  const fitZoom = React.useCallback(() => {
    const el = stageRef.current;
    if (!el) return 1;
    const avail = el.clientWidth - 24;
    const z = Math.min(1, avail / (view.width + 56));
    return Math.max(0.42, +z.toFixed(3));
  }, [view]);

  React.useEffect(() => {
    if (autoFit) setZoom(fitZoom());
  }, [viewKey, autoFit, fitZoom]);

  React.useEffect(() => {
    const onResize = () => { if (autoFit) setZoom(fitZoom()); };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [autoFit, fitZoom]);

  const changeView = (k) => { setSelectedId(null); setViewKey(k); setAutoFit(true); };
  const setZoomManual = (z) => { setAutoFit(false); setZoom(Math.max(0.4, Math.min(1.6, +z.toFixed(2)))); };

  return (
    <div className="app-shell">
      <Sidebar />
      <main className="app-main">
        <TopBar />
        <div style={appCss.header}>
          <div style={appCss.row}>
            <div style={appCss.seg}>
              {Object.values(SUMMIT.views).map((v) => (
                <button
                  key={v.key}
                  type="button"
                  style={{ ...appCss.segBtn, ...(viewKey === v.key ? appCss.segBtnActive : {}) }}
                  onClick={() => changeView(v.key)}
                >{v.label}</button>
              ))}
            </div>
            <div>
              <p style={appCss.kicker}>{view.kicker}</p>
              <h2 style={appCss.title}>Day-one re-roof setup</h2>
            </div>
            <div style={appCss.zoom}>
              <ZoomBtn onClick={() => setZoomManual(zoom - 0.12)} title="Zoom out">−</ZoomBtn>
              <span style={appCss.zoomVal}>{Math.round(zoom * 100)}%</span>
              <ZoomBtn onClick={() => setZoomManual(zoom + 0.12)} title="Zoom in">+</ZoomBtn>
              <button style={{ ...appCss.zoomBtn, width: 'auto', padding: '0 12px', fontSize: 12, fontWeight: 600, ...(autoFit ? { background: '#e8fcf0', borderColor: '#a4f4cd' } : {}) }} onClick={() => setAutoFit(true)} type="button">Fit</button>
            </div>
          </div>
          <Legend roles={roles} />
        </div>

        <div style={appCss.stage} ref={stageRef}>
          <div style={appCss.scroll}>
            <div style={{ transform: `scale(${zoom})`, transformOrigin: 'top left', padding: 28, width: view.width + 56, minHeight: view.height + 56 }}>
              <ProcessMap view={view} roles={roles} selectedId={selectedId} onSelect={setSelectedId} />
            </div>
          </div>
          <DetailDrawer
            nodeId={selectedId}
            view={view}
            roles={roles}
            onClose={() => setSelectedId(null)}
            onOpenView={(k) => { changeView(k); }}
          />
        </div>
      </main>
    </div>
  );
}

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