// v5 — 보유 설비 현황(현재 비활성) / 오시는 길
//
// ※ 보유 설비 현황표(Equipment5)는 민감 정보 우려로 페이지에서 제외한 상태입니다.
//    코드는 그대로 두었으니, 다시 넣으려면
//      1) v5-app.jsx 의 <Catalogue5/> 위에 <Equipment5/> 추가
//      2) v5-sections.jsx 의 nav items 에 { ko:'보유설비', en:'Equipment', id:'equipment' } 추가
//    두 줄만 되돌리면 됩니다.

// ╔══════════════════════════════════════════════════════════════════════╗
// ║  보유 설비 현황 — 실제 설비에 맞게 아래 배열만 수정하시면 됩니다.        ║
// ║  n: 분류 · ko/en: 설비명 · model: 모델 · spec: 주요 사양 · qty: 보유 대수 ║
// ╚══════════════════════════════════════════════════════════════════════╝
const V5_EQUIPMENT = [
  { grp: 'turning', ko: 'CNC 선반', en: 'CNC Lathe', model: 'DOOSAN LYNX 220', spec: 'Ø200 × 510mm · 8" 척', specEn: 'Ø200 × 510mm · 8" chuck', qty: 1 },
  { grp: 'turning', ko: 'CNC 선반', en: 'CNC Lathe', model: 'DOOSAN PUMA GT2100', spec: 'Ø250 × 550mm · FANUC i', specEn: 'Ø250 × 550mm · FANUC i', qty: 1 },
  { grp: 'press',   ko: '유압 프레스', en: 'Hydraulic Press', model: 'HIM HWAIL 200', spec: '200TON · 코일 피더 연동', specEn: '200 ton · with coil feeder', qty: 1 },
  { grp: 'press',   ko: '롤포밍 라인', en: 'Roll-forming Line', model: '자체 구성', specEn: 'In-house built', spec: '판재 연속 성형 · 절단 일체', qty: 1 },
  { grp: 'weld',    ko: 'CO₂ 용접기', en: 'CO₂ Welder', model: '—', spec: '350A · 반자동', specEn: '350A · semi-auto', qty: 2 },
  { grp: 'weld',    ko: 'TIG 용접기', en: 'TIG Welder', model: '—', spec: '300A · 정밀 용접', specEn: '300A · precision', qty: 1 },
  { grp: 'aux',     ko: '천장 크레인', en: 'Overhead Crane', model: '—', spec: '2.8TON', specEn: '2.8 ton', qty: 1 },
  { grp: 'aux',     ko: '밴드쏘 · 절단기', en: 'Band Saw', model: '—', spec: '형강 · 파이프 절단', specEn: 'Section & pipe cutting', qty: 2 },
];

const V5_EQUIP_GROUPS = [
  { id: 'turning', ko: '절삭 가공', en: 'Turning' },
  { id: 'press',   ko: '프레스 · 성형', en: 'Press & Forming' },
  { id: 'weld',    ko: '용접', en: 'Welding' },
  { id: 'aux',     ko: '보조 설비', en: 'Support' },
];

function Equipment5() {
  const t = useV4(); const ko = t.lang !== 'en';
  const total = V5_EQUIPMENT.reduce((a, e) => a + e.qty, 0);

  return (
    <Sec5 id="equipment" bg={D.base}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32, flexWrap: 'wrap', marginBottom: 'clamp(34px,4.5vh,56px)' }}>
        <Rise>
          <Tag5>Equipment</Tag5>
          <H5 style={{ marginTop: 18, maxWidth: 700 }}>
            {ko ? <>보유 설비로<br/>가능 범위를 밝힙니다.</> : <>Our equipment,<br/>stated plainly.</>}
          </H5>
        </Rise>
        <Rise delay={.1}>
          <p style={{ maxWidth: 480, fontSize: 15, lineHeight: 1.78, color: D.bone45 }}>
            {ko
              ? '사양을 보시고 가능 여부가 불확실하면 도면과 함께 문의 주세요.'
              : 'If you are unsure whether a job fits, send the drawing and ask.'}
          </p>
        </Rise>
      </div>

      <Rise delay={.14}>
        <div style={{ border: `1px solid ${D.line2}` }}>
          {/* 표 머리 — 데스크톱에서만 표시 */}
          <div className="g5-eq g5-eq-head mono" style={{
            padding: '14px clamp(14px,1.8vw,24px)', background: D.base2,
            borderBottom: `1px solid ${D.line2}`,
            fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: D.bone28,
          }}>
            <span>{ko ? '분류' : 'Category'}</span>
            <span>{ko ? '설비명' : 'Equipment'}</span>
            <span>{ko ? '모델' : 'Model'}</span>
            <span>{ko ? '주요 사양' : 'Specification'}</span>
            <span style={{ textAlign: 'right' }}>{ko ? '보유' : 'Qty'}</span>
          </div>

          {V5_EQUIP_GROUPS.map(g => {
            const rows = V5_EQUIPMENT.filter(e => e.grp === g.id);
            if (!rows.length) return null;
            return rows.map((e, i) => (
              <EquipRow5 key={g.id + i} e={e} g={g} first={i === 0} ko={ko}/>
            ));
          })}

          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap',
            padding: 'clamp(16px,2vw,22px) clamp(14px,1.8vw,24px)', background: D.base2,
            borderTop: `1px solid ${D.line2}`,
          }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: D.bone28 }}>
              {ko ? `총 ${V5_EQUIPMENT.length}종 · ${total}대 보유` : `${V5_EQUIPMENT.length} types · ${total} units`}
            </span>
            <a href="#contact" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, minHeight: 44, fontSize: 13.5, fontWeight: 600, color: D.bone70 }}
              onMouseEnter={e => e.currentTarget.style.color = D.bone}
              onMouseLeave={e => e.currentTarget.style.color = D.bone70}>
              {ko ? '가능 여부 문의하기' : 'Ask about feasibility'}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h13M12 5.5 18.5 12 12 18.5"/></svg>
            </a>
          </div>
        </div>
      </Rise>
    </Sec5>
  );
}

function EquipRow5({ e, g, first, ko }) {
  const [h, setH] = useState(false);
  return (
    <div className="g5-eq"
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        padding: 'clamp(15px,1.8vh,20px) clamp(14px,1.8vw,24px)',
        borderTop: first ? `1px solid ${D.line2}` : `1px solid ${D.line2}`,
        background: h ? 'rgba(237,235,231,0.025)' : 'transparent',
        transition: 'background .35s',
      }}>
      <span className="mono g5-eq-cat" style={{
        fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase',
        color: first ? D.steel : D.bone28, opacity: first ? 1 : 0,
      }}>{ko ? g.ko : g.en}</span>
      <span style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.02em', color: D.bone }}>
        {ko ? e.ko : e.en}
      </span>
      <span className="mono" style={{ fontSize: 12.5, letterSpacing: '0.02em', color: D.bone70 }}>{e.model}</span>
      <span style={{ fontSize: 13.5, lineHeight: 1.6, color: D.bone45 }}>{ko ? e.spec : (e.specEn || e.spec)}</span>
      <span className="mono g5-eq-qty" style={{ fontSize: 13, fontWeight: 600, color: D.bone70, textAlign: 'right' }}>
        {e.qty}<span style={{ fontSize: 10.5, color: D.bone28, marginLeft: 2 }}>{ko ? '대' : ''}</span>
      </span>
    </div>
  );
}

// ╔══════════════════════════════════════════════════════════════════════╗
// ║  오시는 길 — 주소와 좌표를 바꾸면 지도와 링크가 모두 따라갑니다.        ║
// ║                                                                      ║
// ║  ⚠ lat/lng 는 설문동 일대의 대략적인 좌표입니다. 정확한 위치로 바꾸세요.  ║
// ║    구하는 법: 네이버 지도에서 사업장 검색 → 우클릭 → '이 위치의 좌표'      ║
// ║    또는 구글 지도에서 사업장 우클릭 → 맨 위에 뜨는 숫자 두 개를 복사       ║
// ╚══════════════════════════════════════════════════════════════════════╝
const TSENG_PLACE = {
  name: '태성ENG',
  addr: '경기도 고양시 일산동구 은마길79번길 81, A동 일부(설문동)',
  addrEn: '81 Eunma-gil 79beon-gil, Ilsandong-gu, Goyang-si, Gyeonggi-do, Korea',
  zip: '10252',
  lat: 37.7177,   // 공식 주소DB — 설문동 530-79(은마길79번길 85) 기준
  lng: 126.8035,  // 530-80 은 바로 옆 번지이므로 오차 수십 m 이내
};

// ╔══════════════════════════════════════════════════════════════════════╗
// ║  네이버 지도 키  —  이 한 줄만 채우면 지도가 네이버로 바뀝니다.            ║
// ║                                                                      ║
// ║  발급 절차 (무료, 월 10만회까지)                                       ║
// ║   1. https://console.ncloud.com 가입 → 결제수단 등록                     ║
// ║   2. Services → AI·NAVER API → Maps → '이용 신청'                       ║
// ║   3. Application 등록 → Web Dynamic Map 체크                             ║
// ║   4. '서비스 URL' 에 실제 도메인 입력 (예: https://taesung-eng.co.kr)  ║
// ║      ※ 등록한 도메인에서만 지도가 보입니다. 로컬 테스트시               ║
// ║        http://localhost:5173 같은 주소도 함께 등록하세요.               ║
// ║   5. 발급된 Client ID 를 아래 따옴표 안에 붙여넣기                     ║
// ║                                                                      ║
// ║  비워두면 OpenStreetMap 지도가 그대로 표시됩니다(키 불필요).            ║
// ╚══════════════════════════════════════════════════════════════════════╝
const NAVER_MAP_KEY = '';

// 네이버 지도 — 키가 있을 때만 스크립트를 불러와 그립니다
function NaverMap5({ onFail }) {
  const box = useRef(null);
  useEffect(() => {
    let dead = false;
    const draw = () => {
      if (dead || !box.current || !window.naver || !window.naver.maps) return;
      const pos = new window.naver.maps.LatLng(TSENG_PLACE.lat, TSENG_PLACE.lng);
      const map = new window.naver.maps.Map(box.current, {
        center: pos, zoom: 16,
        zoomControl: true,
        zoomControlOptions: { position: window.naver.maps.Position.TOP_RIGHT },
      });
      new window.naver.maps.Marker({ position: pos, map, title: TSENG_PLACE.name });
    };
    if (window.naver && window.naver.maps) { draw(); return; }
    const s = document.createElement('script');
    s.src = `https://oapi.map.naver.com/openapi/v3/maps.js?ncpKeyId=${NAVER_MAP_KEY}`;
    s.async = true;
    s.onload = draw;
    s.onerror = () => { if (!dead) onFail(); };  // 키·도메인 오류 시 OSM 으로 돼돌아감
    document.head.appendChild(s);
    return () => { dead = true; };
  }, [onFail]);
  return <div ref={box} style={{ width: '100%', height: '100%', minHeight: 420 }}/>;
}

function Location5() {
  const t = useV4(); const ko = t.lang !== 'en';
  const [toast, setToast] = useState(false);
  const [naverFail, setNaverFail] = useState(false);
  const useNaver = !!NAVER_MAP_KEY && !naverFail;
  const q = encodeURIComponent(TSENG_PLACE.addr);

  const copyAddr = async () => {
    try { await navigator.clipboard.writeText(TSENG_PLACE.addr); }
    catch {
      const ta = document.createElement('textarea');
      ta.value = TSENG_PLACE.addr; ta.style.position = 'fixed'; ta.style.opacity = '0';
      document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); } catch {}
      document.body.removeChild(ta);
    }
    setToast(true);
    setTimeout(() => setToast(false), 2200);
  };

  // 지도 앱 딥링크 — API 키 없이 동작합니다
  const maps = [
    { ko: '네이버 지도', en: 'Naver Map', href: `https://map.naver.com/p/search/${q}` },
    { ko: '카카오맵', en: 'KakaoMap', href: `https://map.kakao.com/?q=${q}` },
    { ko: '구글 지도', en: 'Google Maps', href: `https://www.google.com/maps/search/?api=1&query=${q}` },
  ];

  const info = [
    { k: ko ? '주소' : 'Address', v: ko ? TSENG_PLACE.addr : TSENG_PLACE.addrEn, sub: ko ? `우편번호 ${TSENG_PLACE.zip}` : `Zip ${TSENG_PLACE.zip}` },
    { k: ko ? '업무시간' : 'Hours', v: ko ? '평일 08:30 – 18:00' : 'Mon–Fri 08:30–18:00', sub: ko ? '토·일요일 및 공휴일 휴무' : 'Closed weekends & holidays' },
    { k: ko ? '주차' : 'Parking', v: ko ? '사업장 내 주차 가능' : 'On-site parking available', sub: ko ? '대형 차량 진입 가능' : 'Accessible for large vehicles' },
  ];

  return (
    <Sec5 id="location" bg={D.base2}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32, flexWrap: 'wrap', marginBottom: 'clamp(34px,4.5vh,56px)' }}>
        <Rise>
          <Tag5>Location</Tag5>
          <H5 style={{ marginTop: 18, maxWidth: 640 }}>
            {ko ? <>직접 오셔서<br/>확인하셔도 됩니다.</> : <>Come and see<br/>the shop yourself.</>}
          </H5>
        </Rise>
        <Rise delay={.1}>
          <p style={{ maxWidth: 480, fontSize: 15, lineHeight: 1.78, color: D.bone45 }}>
            {ko
              ? <>방문 전 전화 주시면 담당자가 대기합니다.<br/>도면을 들고 오시면 현장에서 바로 검토해 드립니다.</>
              : 'Call ahead and someone will be waiting. Bring the drawing and we review it on the spot.'}
          </p>
        </Rise>
      </div>

      <div className="g5-loc">
        {/* 지도 자리 */}
        <Rise y={30}>
          {/* ══ 지도 ══
              NAVER_MAP_KEY 가 채워지면 네이버 지도, 비어있으면 OpenStreetMap 이 표시됩니다.
              키 발급 절차는 이 파일 상단 NAVER_MAP_KEY 주석 참고. */}
          <div style={{
            position: 'relative', width: '100%', height: '100%', minHeight: 420,
            background: D.base3, border: `1px solid ${D.line2}`, overflow: 'hidden',
          }}>
            {useNaver ? (
              <NaverMap5 onFail={() => setNaverFail(true)}/>
            ) : (
              <iframe
                title={ko ? '태성ENG 위치' : 'TSENG location'}
                src={`https://www.openstreetmap.org/export/embed.html?bbox=${TSENG_PLACE.lng - 0.005}%2C${TSENG_PLACE.lat - 0.0028}%2C${TSENG_PLACE.lng + 0.005}%2C${TSENG_PLACE.lat + 0.0028}&layer=mapnik&marker=${TSENG_PLACE.lat}%2C${TSENG_PLACE.lng}`}
                loading="lazy"
                style={{ width: '100%', height: '100%', minHeight: 420, border: 0, display: 'block', filter: 'grayscale(.28) contrast(1.04)' }}
              ></iframe>
            )}

            {/* 상호·주소 플레이트 — 지도 위에 엹혀 있음 */}
            <div style={{
              position: 'absolute', left: 14, top: 14, maxWidth: 300, pointerEvents: 'none',
              background: 'rgba(11,15,20,.9)', border: `1px solid ${D.line}`,
              padding: '14px 16px', backdropFilter: 'blur(8px)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ display: 'inline-flex', color: D.steel, lineHeight: 0 }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/>
                  </svg>
                </span>
                <span style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.035em', color: D.bone }}>{TSENG_PLACE.name}</span>
              </div>
              <div style={{ marginTop: 7, fontSize: 13, lineHeight: 1.6, color: D.bone45 }}>
                {ko ? TSENG_PLACE.addr : TSENG_PLACE.addrEn}
              </div>
            </div>

            {/* 지도 앱 바로가기 — 하단 고정 */}
            <div style={{
              position: 'absolute', left: 0, right: 0, bottom: 0,
              display: 'flex', flexWrap: 'wrap', gap: 8, padding: 14,
              background: 'linear-gradient(to top, rgba(11,15,20,.94) 40%, transparent 100%)',
            }}>
              {maps.map(m => (
                <a key={m.href} href={m.href} target="_blank" rel="noopener" className="b5"
                  style={{
                    display: 'inline-flex', alignItems: 'center', gap: 7, padding: '11px 16px',
                    fontSize: 12.5, fontWeight: 600, letterSpacing: '-0.012em',
                    border: `1px solid ${D.line}`, color: D.bone, background: 'rgba(11,15,20,.72)',
                    backdropFilter: 'blur(6px)', transition: 'background .3s, color .3s',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = D.bone; e.currentTarget.style.color = D.base; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'rgba(11,15,20,.72)'; e.currentTarget.style.color = D.bone; }}>
                  {ko ? m.ko : m.en}
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M7 17 17 7M8 7h9v9"/>
                  </svg>
                </a>
              ))}
            </div>
          </div>
        </Rise>

        {/* 방문 정보 */}
        <Rise delay={.1} y={30}>
          <div>
            {info.map((r, i) => (
              <div key={r.k} style={{ padding: 'clamp(18px,2.4vh,26px) 0', borderTop: i === 0 ? 'none' : `1px solid ${D.line2}` }}>
                <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: D.steel, marginBottom: 10 }}>{r.k}</div>
                <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.025em', lineHeight: 1.55, color: D.bone }}>{r.v}</div>
                {r.sub && <div style={{ marginTop: 6, fontSize: 13.5, color: D.bone45 }}>{r.sub}</div>}
              </div>
            ))}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 24, paddingTop: 24, borderTop: `1px solid ${D.line2}` }}>
              <button onClick={copyAddr} className="b5" style={{
                display: 'inline-flex', alignItems: 'center', gap: 8, padding: '13px 20px', cursor: 'pointer',
                fontSize: 13, fontWeight: 600, background: 'transparent', color: D.bone, border: `1px solid ${D.line}`,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                </svg>
                {ko ? '주소 복사' : 'Copy address'}
              </button>
              <B5 href="tel:0319623951" tone="solid">{ko ? '전화 걸기' : 'Call us'}</B5>
            </div>
          </div>
        </Rise>
      </div>

      <div aria-live="polite" style={{
        position: 'fixed', left: '50%', bottom: 92, zIndex: 400,
        transform: `translateX(-50%) translateY(${toast ? '0' : '14px'})`,
        opacity: toast ? 1 : 0, pointerEvents: 'none',
        transition: 'opacity .3s ease, transform .3s cubic-bezier(.2,.7,.3,1)',
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '13px 20px', background: D.bone, color: D.base,
        fontSize: 14, fontWeight: 600, letterSpacing: '-0.02em',
        boxShadow: '0 12px 34px rgba(0,0,0,.45)', whiteSpace: 'nowrap',
      }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
        {ko ? '주소가 복사되었습니다' : 'Address copied'}
      </div>
    </Sec5>
  );
}

Object.assign(window, { V5_EQUIPMENT, V5_EQUIP_GROUPS, Equipment5, EquipRow5, TSENG_PLACE, Location5 });
