// app/erp.jsx — 리본 렌터카 ERP 데스크톱 셸 (챗봇 백드롭) + 요소 스포트라이트
// window.RibbonERP 로 노출.

const { useRef: useRefE, useEffect: useEffectE, useState: useStateE } = React;
const { Icon: IconE } = window.RibbonChat;

const NAV = [
  { label: '대시보드', d: 'M3 13h8V3H3zM13 21h8V11h-8zM13 3v6h8V3zM3 17v4h8v-4z', active: true },
  { label: '인벤토리', d: 'M3 7l9-4 9 4-9 4zM3 7v10l9 4 9-4V7M12 11v10' },
  { label: '예약', d: 'M8 2v4M16 2v4M3 9h18M5 5h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z' },
  { label: '정비', d: 'M14 6a4 4 0 0 1-5.3 5.3L4 16v4h4l4.7-4.7A4 4 0 0 1 18 10l3-3-3-3-3 3z' },
  { label: '매출', d: 'M3 3v18h18M7 14l3-3 3 3 5-6' },
  { label: '설정', d: 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM19 12a7 7 0 0 0-.1-1l2-1.6-2-3.4-2.4 1a7 7 0 0 0-1.7-1L16 3H8l-.8 2.4a7 7 0 0 0-1.7 1l-2.4-1-2 3.4L3.1 11a7 7 0 0 0 0 2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 1.7 1L8 21h8l.8-2.4a7 7 0 0 0 1.7-1l2.4 1 2-3.4-2-1.6a7 7 0 0 0 .1-1z' },
];

function StatTone(status) {
  return status === 'hot' ? { t: '포화', bg: 'rgba(204,120,92,0.14)', fg: 'var(--accent)' }
    : status === 'low' ? { t: '여유', bg: 'rgba(93,184,114,0.14)', fg: '#3f8a52' }
    : { t: '정상', bg: 'var(--surface-card)', fg: 'var(--text-muted)' };
}

function RibbonERP({ spotlight, dense, tenant, onTenantChange }) {
  const D = window.RibbonData;
  const tn = tenant || D.TENANTS[0]; // 현재 업체(안전 기본값)
  const rowRefs = useRefE({});
  const [annot, setAnnot] = useStateE(null); // {top, left, width}

  useEffectE(() => {
    if (!spotlight) { setAnnot(null); return; }
    const el = rowRefs.current[spotlight];
    if (el) {
      const p = el.offsetParent;
      setAnnot({ top: el.offsetTop, left: el.offsetLeft, width: el.offsetWidth, height: el.offsetHeight });
    }
  }, [spotlight]);

  const pad = dense ? 16 : 24;
  return (
    <div style={{ height: '100%', display: 'flex', background: 'var(--surface-page)', fontFamily: 'var(--font-sans)', overflow: 'hidden' }}>
      {/* 좌측 네비 레일 */}
      <nav style={{ width: 220, flexShrink: 0, borderRight: '1px solid var(--border-hairline)', background: 'var(--surface-soft)',
        display: 'flex', flexDirection: 'column', padding: '20px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '0 8px 20px' }}>
          <div style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M12 2l2 6 6-1-4 5 4 5-6-1-2 6-2-6-6 1 4-5-4-5 6 1z"/></svg>
          </div>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 21, letterSpacing: '-0.5px', color: 'var(--text-heading)' }}>Ribbon</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {NAV.map((n, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 11px', borderRadius: 'var(--radius-md)',
              background: n.active ? 'var(--surface-page)' : 'transparent', border: n.active ? '1px solid var(--border-hairline)' : '1px solid transparent',
              color: n.active ? 'var(--text-heading)' : 'var(--text-muted)', fontSize: 13.5, fontWeight: n.active ? 600 : 500, cursor: 'pointer' }}>
              <IconE d={n.d} size={17} color={n.active ? 'var(--accent)' : 'var(--text-muted)'} />{n.label}
            </div>
          ))}
        </div>
        <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 9, padding: '8px', borderTop: '1px solid var(--border-hairline)' }}>
          <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--surface-card-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 600, color: 'var(--text-body)' }}>강</div>
          <div style={{ lineHeight: 1.3 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-heading)' }}>강민재</div>
            <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>플릿 매니저</div>
          </div>
        </div>
      </nav>

      {/* 메인 콘텐츠 */}
      <div style={{ flex: 1, overflow: 'auto', position: 'relative' }}>
        {/* 상단 바 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: `16px ${pad}px`, borderBottom: '1px solid var(--border-hairline)', position: 'sticky', top: 0, background: 'var(--surface-page)', zIndex: 5 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, letterSpacing: '-0.4px', color: 'var(--text-heading)' }}>플릿 대시보드</div>
            <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 1 }}>2026년 6월 · {tn.name} · {tn.region}</div>
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10 }}>
            {/* 업체(테넌트) 전환 */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <span style={{ fontSize: 11.5, color: 'var(--text-faint)', fontWeight: 600 }}>업체</span>
              <select value={tn.id} onChange={e => onTenantChange && onTenantChange(e.target.value)} title="업체 전환"
                style={{ height: 36, padding: '0 12px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-hairline)',
                  background: 'var(--surface-page)', fontFamily: 'var(--font-sans)', fontSize: 12.5, fontWeight: 600,
                  color: 'var(--text-heading)', cursor: 'pointer', outline: 'none' }}>
                {D.TENANTS.map(t => <option key={t.id} value={t.id}>{t.name + ' · ' + t.region}</option>)}
              </select>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '7px 12px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-hairline)', fontSize: 12.5, color: 'var(--text-muted)' }}>
              <IconE d="M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM21 21l-4.5-4.5" size={15} color="var(--text-faint)" />검색
            </div>
            <div style={{ width: 36, height: 36, borderRadius: '50%', border: '1px solid var(--border-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <IconE d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.7 21a2 2 0 0 1-3.4 0" size={17} color="var(--text-muted)" />
            </div>
          </div>
        </div>

        <div style={{ padding: pad }}>
          {/* KPI 행 */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: pad }}>
            {D.ERP_KPIS.map((k, i) => (
              <div key={i} style={{ background: 'var(--surface-page)', border: '1px solid var(--border-hairline)', borderRadius: 'var(--radius-lg)', padding: '16px 18px' }}>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 500, marginBottom: 10 }}>{k.label}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 32, letterSpacing: '-0.8px', color: 'var(--text-heading)', lineHeight: 1 }}>{k.value}</span>
                  <span style={{ fontSize: 13, color: 'var(--text-muted)', fontWeight: 500 }}>{k.unit}</span>
                </div>
                <div style={{ marginTop: 9, fontSize: 12, fontWeight: 600, color: k.dir === 'down' ? 'var(--color-error)' : 'var(--color-success)' }}>
                  {k.dir === 'down' ? '▾' : '▴'} {k.delta} <span style={{ color: 'var(--text-faint)', fontWeight: 500 }}>vs 전월</span>
                </div>
              </div>
            ))}
          </div>

          {/* 차종별 플릿 현황 (스포트라이트 타깃) */}
          <div style={{ position: 'relative', zIndex: spotlight ? 25 : 1, background: 'var(--surface-page)', border: '1px solid var(--border-hairline)', borderRadius: 'var(--radius-lg)', overflow: 'visible', marginBottom: pad }}>
            <div style={{ padding: '15px 20px', borderBottom: '1px solid var(--border-hairline)', fontSize: 15, fontWeight: 600, color: 'var(--text-heading)' }}>차종별 플릿 현황</div>
            <div style={{ padding: '6px 8px' }}>
              {/* header */}
              <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1.6fr 1fr 0.9fr', padding: '8px 14px', fontSize: 11.5, fontWeight: 600, color: 'var(--text-faint)' }}>
                <span>차종</span><span>보유</span><span>가동률</span><span>유휴</span><span>상태</span>
              </div>
              {D.FLEET.map((f) => {
                const tone = StatTone(f.status);
                const hl = spotlight === f.id;
                return (
                  <div key={f.id} ref={el => rowRefs.current[f.id] = el}
                    style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1.6fr 1fr 0.9fr', alignItems: 'center', padding: '11px 14px',
                      borderRadius: 'var(--radius-md)', position: 'relative', zIndex: hl ? 30 : 1,
                      background: hl ? 'rgba(204,120,92,0.12)' : 'transparent',
                      boxShadow: hl ? '0 0 0 2px var(--accent), 0 8px 24px rgba(204,120,92,0.22)' : 'none',
                      transition: 'box-shadow .3s ease, background .3s ease' }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-heading)' }}>{f.seg}</span>
                    <span style={{ fontSize: 13, color: 'var(--text-body)' }}>{f.count}대</span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                      <div style={{ flex: 1, maxWidth: 110, height: 6, borderRadius: 4, background: 'var(--surface-card)', overflow: 'hidden' }}>
                        <div style={{ width: f.util + '%', height: '100%', borderRadius: 4, background: f.util > 88 ? 'var(--accent)' : f.util < 75 ? 'var(--color-amber)' : 'var(--color-teal)' }} />
                      </div>
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-heading)' }}>{f.util}%</span>
                    </div>
                    <span style={{ fontSize: 13, color: 'var(--text-body)' }}>{f.idle}대</span>
                    <span><span style={{ fontSize: 11.5, fontWeight: 600, padding: '3px 10px', borderRadius: 'var(--radius-pill)', background: tone.bg, color: tone.fg }}>{tone.t}</span></span>
                  </div>
                );
              })}
            </div>

            {/* 챗봇 주석 콜아웃 */}
            {spotlight && annot && (
              <div style={{ position: 'absolute', top: annot.top - 8, left: annot.left + annot.width - 16, transform: 'translateX(-100%)', zIndex: 40, pointerEvents: 'none' }}>
                <div className="rb-callout" style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface-dark)', color: 'var(--text-on-dark)',
                  padding: '9px 13px', borderRadius: 'var(--radius-md)', boxShadow: '0 8px 24px rgba(20,20,19,0.25)', whiteSpace: 'nowrap' }}>
                  <window.RibbonChat.Spike size={15} color="var(--color-amber)" />
                  <span style={{ fontSize: 12.5, fontWeight: 600 }}>여기 — 재고 임박, 증차 검토 대상</span>
                </div>
              </div>
            )}
          </div>

          {/* 하단 2단: 최근 예약 + 안내 */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: pad }}>
            <div style={{ background: 'var(--surface-page)', border: '1px solid var(--border-hairline)', borderRadius: 'var(--radius-lg)' }}>
              <div style={{ padding: '15px 20px', borderBottom: '1px solid var(--border-hairline)', fontSize: 15, fontWeight: 600, color: 'var(--text-heading)' }}>오늘의 픽업 예약</div>
              <div>
                {D.RECENT_RES.map((r, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 20px', borderBottom: i < D.RECENT_RES.length - 1 ? '1px solid var(--border-hairline-soft)' : 'none' }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-faint)' }}>{r.id}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-heading)' }}>{r.car}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{r.cust} · {r.loc}</div>
                    </div>
                    <div style={{ fontSize: 12.5, color: 'var(--text-body)', fontWeight: 500 }}>{r.pickup}</div>
                    <span style={{ fontSize: 11, fontWeight: 600, padding: '3px 9px', borderRadius: 'var(--radius-pill)',
                      background: r.state === '확정' ? 'rgba(93,184,114,0.14)' : 'rgba(212,160,23,0.16)', color: r.state === '확정' ? '#3f8a52' : '#a07c12' }}>{r.state}</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', padding: 20, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
              <window.RibbonChat.Spike size={22} />
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, letterSpacing: '-0.3px', color: 'var(--text-heading)', margin: '12px 0 6px', lineHeight: 1.3 }}>데이터가 궁금하신가요?</div>
              <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>우측 리본 AI에게 물어보면 차트·표로 바로 답해 드려요.</div>
            </div>
          </div>
        </div>

        {/* 스포트라이트 시 화면 디밍 */}
        {spotlight && <div style={{ position: 'absolute', inset: 0, background: 'rgba(20,20,19,0.18)', zIndex: 20, pointerEvents: 'none', transition: 'opacity .3s' }} />}
      </div>
    </div>
  );
}

window.RibbonERP = { RibbonERP };
