/* global React, Ic, PageHero, useT */

// ── Business: Core capabilities ──────────────────────────────
const CAP_DEFS = [
  { id: "volume",  key: "cap_volume",  withSmall: true },
  { id: "spec",    key: "cap_spec" },
  { id: "knowhow", key: "cap_knowhow" },
  { id: "invest",  key: "cap_invest" },
  { id: "system",  key: "cap_system" },
];

function CoreVisual({ highlighted, setHighlighted }) {
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    const onMove = (e) => {
      const rect = wrap.getBoundingClientRect();
      const dx = ((e.clientX - rect.left) / rect.width - 0.5) * 2;
      const dy = ((e.clientY - rect.top) / rect.height - 0.5) * 2;
      const angle = Math.atan2(dy, dx) * (180 / Math.PI);
      const distance = Math.min(1, Math.sqrt(dx * dx + dy * dy));
      wrap.style.setProperty("--mx", dx.toFixed(3));
      wrap.style.setProperty("--my", dy.toFixed(3));
      wrap.style.setProperty("--ang", (angle * distance * 0.08).toFixed(2) + "deg");
      wrap.style.setProperty("--tilt-x", (dy * -6).toFixed(2) + "deg");
      wrap.style.setProperty("--tilt-y", (dx * 6).toFixed(2) + "deg");
    };
    const onLeave = () => {
      wrap.style.setProperty("--mx", "0");
      wrap.style.setProperty("--my", "0");
      wrap.style.setProperty("--ang", "0deg");
      wrap.style.setProperty("--tilt-x", "0deg");
      wrap.style.setProperty("--tilt-y", "0deg");
    };
    wrap.addEventListener("mousemove", onMove);
    wrap.addEventListener("mouseleave", onLeave);
    return () => {
      wrap.removeEventListener("mousemove", onMove);
      wrap.removeEventListener("mouseleave", onLeave);
    };
  }, []);

  const rings = React.useMemo(() => {
    const out = [];
    const cx = 250, cy = 280;
    const spacing = 5;
    const dotR = 0.7;
    out.push({ x: cx, y: cy, r: dotR });
    for (let r = 1; r <= 30; r++) {
      const radius = r * spacing;
      const n = Math.max(6, Math.round(2 * Math.PI * radius / spacing));
      for (let i = 0; i < n; i++) {
        const a = i / n * Math.PI * 2 + r % 2 * (Math.PI / n);
        out.push({ x: cx + Math.cos(a) * radius, y: cy + Math.sin(a) * radius, r: dotR });
      }
    }
    return out;
  }, []);

  const zoomDots = React.useMemo(() => {
    const out = [];
    const cx = 380, cy = 100, dotR = 2.3, spacing = 7;
    out.push({ x: cx, y: cy, r: dotR });
    for (let r = 1; r <= 5; r++) {
      const radius = r * spacing;
      const n = Math.max(6, Math.round(2 * Math.PI * radius / spacing));
      for (let i = 0; i < n; i++) {
        const a = i / n * Math.PI * 2 + r % 2 * (Math.PI / n);
        const x = cx + Math.cos(a) * radius;
        const y = cy + Math.sin(a) * radius;
        if (Math.hypot(x - cx, y - cy) <= 36) out.push({ x, y, r: dotR });
      }
    }
    return out;
  }, []);

  return (
    <div className="corevisual" ref={wrapRef} data-highlight={highlighted || ""}>
      <div className="corevisual__bg" />
      <div className="corevisual__svg-wrap">
        <svg viewBox="0 0 500 500" className="corevisual__svg" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <radialGradient id="cap-rim" cx="50%" cy="42%" r="58%">
              <stop offset="55%" stopColor="#D5D8DE" />
              <stop offset="80%" stopColor="#B6BAC2" />
              <stop offset="100%" stopColor="#7E848F" />
            </radialGradient>
            <radialGradient id="cap-inset" cx="50%" cy="42%" r="48%">
              <stop offset="0%" stopColor="#EEF0F4" />
              <stop offset="70%" stopColor="#CFD2D9" />
              <stop offset="100%" stopColor="#9CA0AB" />
            </radialGradient>
            <radialGradient id="cap-hi" cx="50%" cy="32%" r="38%">
              <stop offset="0%" stopColor="#ffffff" stopOpacity="0.7" />
              <stop offset="100%" stopColor="#ffffff" stopOpacity="0" />
            </radialGradient>
            <radialGradient id="zoom-bg" cx="50%" cy="40%" r="55%">
              <stop offset="0%" stopColor="#FDFDFE" />
              <stop offset="100%" stopColor="#E6E8ED" />
            </radialGradient>
            <path id="arc-quality" d="M 90 290 A 175 175 0 0 1 200 130" fill="none" />
            <path id="arc-tech" d="M 295 130 A 175 175 0 0 1 405 290" fill="none" />
            <path id="arc-knowhow" d="M 405 290 A 175 175 0 0 1 295 445" fill="none" />
          </defs>

          <g className="cv-disc">
            <circle cx="250" cy="280" r="210" fill="url(#cap-rim)" />
            <circle cx="250" cy="280" r="210" fill="none" stroke="#7C8290" strokeWidth="0.6" />
            <circle cx="250" cy="280" r="172" fill="url(#cap-inset)" />
            <circle cx="250" cy="280" r="172" fill="none" stroke="#8E939E" strokeWidth="0.6" />
            <circle cx="250" cy="280" r="172" fill="url(#cap-hi)" pointerEvents="none" />

            <g className="cv-holes"
            onMouseEnter={() => setHighlighted("volume")}
            onMouseLeave={() => setHighlighted(null)}
            style={{ cursor: "pointer" }}>
              <g className="cv-holes__main" fill="#3A4150">
                {rings.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={p.r} />)}
              </g>
            </g>
          </g>

          <g className="cv-labels" fill="#5A5C63" style={{ font: "700 13px var(--font-sans)", letterSpacing: "0.22em" }}>
          </g>

          <g className="cv-zoom"
          onMouseEnter={() => setHighlighted("spec")}
          onMouseLeave={() => setHighlighted(null)}
          style={{ cursor: "pointer" }}>
            <g className="cv-zoom__lead" stroke="#5A5C63" strokeWidth="0.6" fill="none">
              <line x1="260" y1="270" x2="345" y2="135" strokeDasharray="2.5 2.5" />
              <line x1="240" y1="290" x2="345" y2="135" strokeDasharray="2.5 2.5" />
            </g>
            <circle cx="380" cy="100" r="58" fill="url(#zoom-bg)" stroke="#0066FF" strokeWidth="1.6" />
            <g className="cv-zoom__pattern" fill="#3A4150">
              {zoomDots.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={p.r} />)}
            </g>
          </g>

          <g className="cv-spec"
          onMouseEnter={() => setHighlighted("spec")}
          onMouseLeave={() => setHighlighted(null)}
          style={{ cursor: "pointer" }}>
          </g>
        </svg>
      </div>
    </div>);

}

function BusinessCore() {
  const t = useT();
  const [highlighted, setHighlighted] = React.useState(null);
  return (
    <section className="psection" data-screen-label="01 Core">
      <div className="container">
        <div className="psection__head">
          <span className="eyebrow">{t("business_core.eyebrow")}</span>
          <h2 className="capabilities__hl">{t("business_core.title_a")}<em>{t("business_core.title_emph")}</em>{t("business_core.title_b")}</h2>
          <p className="capabilities__lead" style={{ opacity: "1", width: "860px" }}>{t("business_core.lead")}</p>
        </div>
        <div className="capabilities-v2">
          <CoreVisual highlighted={highlighted} setHighlighted={setHighlighted} />
          <div className="cap-stats">
            {CAP_DEFS.map((c) => <div
              key={c.id}
              className={`cap-stat ${highlighted === c.id ? "cap-stat--hl" : ""}`}
              onMouseEnter={() => setHighlighted(c.id)}
              onMouseLeave={() => setHighlighted(null)}
              data-id={c.id}>
                <span className="lbl">{t(`business_core.${c.key}_lbl`)}</span>
                <span className="val">{t(`business_core.${c.key}_val`)}{c.withSmall && <small style={{ fontSize: "16px" }}>{t(`business_core.${c.key}_small`)}</small>}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

// ── Business: Differentiated Infrastructure ──────────────────
const INFRA_GROUPS = [
  { catKey: "cat_env",     items: [
    { nameKey: "n1", descKey: "d1" },
    { nameKey: "n2", descKey: "d2" },
    { nameKey: "n3", descKey: "d3" },
    { nameKey: "n4", descKey: "d4" },
  ]},
  { catKey: "cat_clean",   items: [
    { nameKey: "n5", descKey: "d5", stepsKey: "d5_steps" },
    { nameKey: "n6", descKey: "d6" },
  ]},
  { catKey: "cat_measure", items: [
    { nameKey: "n7", descKey: "d7" },
    { nameKey: "n8", descKey: "d8" },
  ]},
];

function BusinessInfra() {
  const t = useT();
  const [active, setActive] = React.useState(0);
  const groupRefs = React.useRef([]);

  React.useEffect(() => {
    const els = groupRefs.current.filter(Boolean);
    if (!els.length) return;
    const onScroll = () => {
      const trigger = window.innerHeight * 0.35;
      let bestIdx = -1;
      let bestDist = Infinity;
      els.forEach((el, i) => {
        const r = el.getBoundingClientRect();
        if (r.top <= trigger && r.bottom > 0) {
          const dist = Math.abs(r.top - trigger);
          if (dist < bestDist) { bestDist = dist; bestIdx = i; }
        }
      });
      // No group intersects the trigger: above all → first, below all → last
      if (bestIdx === -1) {
        const firstTop = els[0].getBoundingClientRect().top;
        bestIdx = firstTop > trigger ? 0 : els.length - 1;
      }
      setActive(bestIdx);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  const onNavClick = (idx) => {
    const el = groupRefs.current[idx];
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 120;
    window.scrollTo({ top: y, behavior: "smooth" });
  };

  return (
    <section className="psection psection--alt" data-screen-label="02 Infrastructure">
      <div className="container">
        <div className="psection__head">
          <span className="eyebrow">{t("business_infra.eyebrow")}</span>
          <h2>{t("business_infra.title")}</h2>
          <p>{t("business_infra.subtitle")}</p>
        </div>
        <div className="infra-v2">
          <aside className="infra-v2__nav">
            <ul>
              {INFRA_GROUPS.map((g, i) =>
                <li key={g.catKey} className={`infra-v2__nav-item ${active === i ? "is-active" : ""}`}>
                  <button type="button" onClick={() => onNavClick(i)}>
                    <span className="infra-v2__nav-dot" />
                    <span className="infra-v2__nav-label">{t(`business_infra.${g.catKey}`)}</span>
                    <span className="infra-v2__nav-count">{String(g.items.length).padStart(2, "0")}</span>
                  </button>
                </li>
              )}
            </ul>
          </aside>
          <div className="infra-v2__list">
            {INFRA_GROUPS.map((g, i) =>
              <div
                key={g.catKey}
                ref={(el) => groupRefs.current[i] = el}
                data-idx={i}
                className="infra-v2__group"
              >
                <div className="infra-v2__group-head">
                  <span className="infra-v2__group-cat">{t(`business_infra.${g.catKey}`)}</span>
                  <span className="infra-v2__group-idx">{String(i + 1).padStart(2, "0")} / {String(INFRA_GROUPS.length).padStart(2, "0")}</span>
                </div>
                <div className="infra-v2__cards">
                  {g.items.map((it, j) =>
                    <article key={j} className="infra-v2__card fade-up" style={{ "--d": `${j * 80}ms` }}>
                      <h4>{t(`business_infra.${it.nameKey}`)}</h4>
                      <p>{t(`business_infra.${it.descKey}`)}</p>
                      {it.stepsKey && (
                        <div className="step-flow">
                          {t(`business_infra.${it.stepsKey}`).split("|").map((step, si, arr) => (
                            <React.Fragment key={si}>
                              <span className="step-flow__item">
                                <span className="step-flow__num">{si + 1}</span>
                                <span className="step-flow__label">{step.trim()}</span>
                              </span>
                              {si < arr.length - 1 && <span className="step-flow__sep">›</span>}
                            </React.Fragment>
                          ))}
                        </div>
                      )}
                    </article>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

// ── Business: Process Flow ───────────────────────────────────
const FLOW_TOP_KEYS = [
  { n: "01", key: "s1", accent: true },
  { n: "02", key: "s2" },
  { n: "03", key: "s3" },
  { n: "04", key: "s4" },
  { n: "05", key: "s5" },
];
const FLOW_MID_KEYS = [
  { n: "06", key: "s6" },
  { n: "07", key: "s7" },
  { n: "08", key: "s8" },
];
const FLOW_BOT_KEYS = [
  { n: "09", key: "s9" },
  { n: "10", key: "s10" },
  { n: "11", key: "s11", accent: true },
];

function FlowCard({ n, title, accent, i }) {
  return (
    <div className={`flow-u__step ${accent ? "flow-u__step--accent" : ""}`} style={{ "--i": i }}>
      <span className="flow-u__num">{n}</span>
      <span className="flow-u__name">{title}</span>
    </div>);

}

function BusinessFlow() {
  const t = useT();
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    if (!wrapRef.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { e.target.classList.add("in"); io.disconnect(); }
    }, { threshold: 0.2 });
    io.observe(wrapRef.current);
    return () => io.disconnect();
  }, []);
  return (
    <section className="psection" data-screen-label="03 Flow">
      <div className="container">
        <div className="psection__head">
          <span className="eyebrow">{t("business_flow.eyebrow")}</span>
          <h2>{t("business_flow.title")}</h2>
          <p>{t("business_flow.subtitle")}</p>
        </div>

        <div className="flow-u" ref={wrapRef}>
          <div className="flow-u__row flow-u__row--top">
            {FLOW_TOP_KEYS.map((s, i) =>
            <div key={s.n} className="flow-u__cell">
                <FlowCard n={s.n} title={t(`business_flow.${s.key}`)} accent={s.accent} i={i} />
                {i < FLOW_TOP_KEYS.length - 1 && <div className="flow-u__h-conn" style={{ "--i": i + 0.5 }} />}
              </div>
            )}
          </div>

          <div className="flow-u__drop flow-u__drop--right">
            <div className="flow-u__v-conn" style={{ "--i": 5 }} />
          </div>

          <div className="flow-u__row flow-u__row--mid">
            <div className="flow-u__group">
              <span className="flow-u__group-label" style={{ fontSize: "25px" }}><span style={{ color: "rgba(0, 0, 0, 0.812)" }}>{t("business_flow.welding_group")}</span></span>
              <div className="flow-u__group-inner">
                <div className="flow-u__cell">
                  <FlowCard n={FLOW_MID_KEYS[2].n} title={t(`business_flow.${FLOW_MID_KEYS[2].key}`)} i={7} />
                </div>
                <div className="flow-u__cell">
                  <FlowCard n={FLOW_MID_KEYS[1].n} title={t(`business_flow.${FLOW_MID_KEYS[1].key}`)} i={6} />
                  <div className="flow-u__h-conn flow-u__h-conn--rev" style={{ "--i": 6.5 }} />
                </div>
                <div className="flow-u__cell">
                  <FlowCard n={FLOW_MID_KEYS[0].n} title={t(`business_flow.${FLOW_MID_KEYS[0].key}`)} i={5} />
                  <div className="flow-u__h-conn flow-u__h-conn--rev" style={{ "--i": 5.5 }} />
                </div>
              </div>
            </div>
          </div>

          <div className="flow-u__drop flow-u__drop--left">
            <div className="flow-u__v-conn" style={{ "--i": 8 }} />
          </div>

          <div className="flow-u__row flow-u__row--bot">
            {FLOW_BOT_KEYS.map((s, i) =>
            <div key={s.n} className="flow-u__cell">
                <FlowCard n={s.n} title={t(`business_flow.${s.key}`)} accent={s.accent} i={8 + i} />
                {i < FLOW_BOT_KEYS.length - 1 && <div className="flow-u__h-conn" style={{ "--i": 8 + i + 0.5 }} />}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

// ── Business: Products ───────────────────────────────────────
// Material strings are kept as-is (technical, language-neutral).
const SHOWER_HEADS = [
  { id: "sh-flat",       keyBase: "sh_flat",   material: "Al6061",         process: "CVD / ALD", showHole: true,  badge: "Ni PLATING" },
  { id: "sh-md",         keyBase: "sh_md",     material: "Al6061",         process: "CVD / ALD", showHole: true,  badge: "Ni PLATING" },
  { id: "sh-arc",        keyBase: "sh_arc",    material: "Al6061",         process: "CVD",       showHole: true },
  { id: "sh-detachable", keyBase: "sh_detach", material: "Al6061 · Al5052", process: "CVD",       showHole: true },
  { id: "sh-welding",    keyBase: "sh_weld",   material: "Al6061 · Al5052", process: "CVD",       showHole: true,  badge: "EBEAM WELDING" },
  { id: "sh-dual",       keyBase: "sh_dual",   material: "Al6061 · SUS",   process: "CVD / ALD", showHole: true,  badge: "EBEAM WELDING" },
];

const CORE_PARTS = [
  { id: "gasbox",    keyBase: "gasbox",    material: "Al6061 · Al5052", process: "CVD",         badges: ["EBEAM WELDING", "Ni PLATING"] },
  { id: "susceptor", keyBase: "susceptor", material: "Al6061",          process: "CVD / ALD",   badge: "EBEAM WELDING", wide: true },
  { id: "liner",     keyBase: "liner",     material: "Al6061 · SUS",    process: "Etch",        showHole: true },
  { id: "plate",     keyBase: "plate",     material: "Al6061",          process: "CVD",         showHole: true },
  { id: "baffle",    keyBase: "baffle",    material: "Al6061",          process: "CVD / Etch",  showHole: true },
];

const PARTS = [
  { id: "housing-cool", keyBase: "housing",   material: "Al6061",        process: "Machining", wide: true },
  { id: "p-ring",       keyBase: "ring",      material: "PEEK · Al6061", process: "CVD" },
  { id: "p-plate",      keyBase: "pplate",    material: "Al6061",        process: "CVD", wide: true },
  { id: "p-insulator",  keyBase: "insulator", material: "TEFLON",        process: "CVD" },
];

function ProductCard({ p, i = 0 }) {
  const t = useT();
  const name = t(`business_products.${p.keyBase}_name`);
  const desc = t(`business_products.${p.keyBase}_desc`);
  const hole = p.showHole ? t(`business_products.${p.keyBase}_hole`) : "";
  return (
    <div className={`product ${p.wide ? "product--wide" : ""} fade-up delay-${i % 3 + 1}`}>
      <div className="product__img">
        {(p.badges || (p.badge ? [p.badge] : [])).map((b, bi) =>
        <span key={bi} className={`product__badge product__badge--${b === "EBEAM WELDING" ? "eb" : "ni"}`} style={{ top: 14 + bi * 30 + "px" }}>{b}</span>
        )}
        {p.wide ?
        <div className="product__img-split">
            <image-slot id={`product-${p.id}-1`} shape="rect" placeholder={`${name}${t("business_products.img_split_suffix_1")}`}></image-slot>
            <image-slot id={`product-${p.id}-2`} shape="rect" placeholder={`${name}${t("business_products.img_split_suffix_2")}`}></image-slot>
          </div> :

        <image-slot id={`product-${p.id}`} shape="rect" placeholder={`${name}${t("business_products.img_suffix")}`}></image-slot>
        }
      </div>
      <div className="product__body">
        <h3 className="product__name">{name}</h3>
        <div className="product__meta">
          <span className="lbl">{t("business_products.lbl_material")}</span>
          <span className="val">{p.material}</span>
          <span className="lbl">{t("business_products.lbl_process")}</span>
          <span className="val">{p.process}</span>
          {p.showHole && hole && <><span className="lbl">{t("business_products.lbl_hole")}</span>
          <span className="val">{hole}</span></>}
        </div>
        <p className="product__desc">{desc}</p>
      </div>
    </div>);

}

function BusinessProducts() {
  const t = useT();
  return (
    <section className="psection psection--alt" id="products" data-screen-label="04 Products">
      <div className="container">
        <div className="psection__head">
          <span className="eyebrow">{t("business_products.eyebrow")}</span>
          <h2>{t("business_products.title")}</h2>
          <p>{t("business_products.subtitle")}</p>
        </div>

        <div className="products-cat">
          <div className="products-cat__head">
            <span className="products-cat__num">01</span>
            <h3 className="products-cat__title">{t("business_products.cat_shower")}</h3>
            <span className="products-cat__count">{SHOWER_HEADS.length}{t("business_products.count_suffix")}</span>
          </div>
          <div className="products">
            {SHOWER_HEADS.map((p, i) => <ProductCard key={p.id} p={p} i={i} />)}
          </div>
        </div>

        <div className="products-cat">
          <div className="products-cat__head">
            <span className="products-cat__num">02</span>
            <h3 className="products-cat__title">{t("business_products.cat_core")}</h3>
            <span className="products-cat__count">{CORE_PARTS.length}{t("business_products.count_suffix")}</span>
          </div>
          <div className="products">
            {CORE_PARTS.map((p, i) => <ProductCard key={p.id} p={p} i={i} />)}
          </div>
        </div>

        <div className="products-cat">
          <div className="products-cat__head">
            <span className="products-cat__num">03</span>
            <h3 className="products-cat__title">{t("business_products.cat_parts")}</h3>
            <span className="products-cat__count">{PARTS.length}{t("business_products.count_suffix")}</span>
          </div>
          <div className="products">
            {PARTS.map((p, i) => <ProductCard key={p.id} p={p} i={i} />)}
          </div>
        </div>
      </div>
    </section>);

}

// ── Business: CTA ────────────────────────────────────────────
function BusinessCTA() {
  const t = useT();
  return (
    <section className="finalcta" data-screen-label="05 CTA">
      <div className="container">
        <div className="finalcta__inner">
          <div>
            <h2>{t("business_cta.title_a")}<br />{t("business_cta.title_b")}</h2>
            <p>{t("business_cta.body")}</p>
          </div>
          <div className="finalcta__actions">
            <a href="mailto:tm@themyong.co.kr" className="btn btn--on-dark"><Ic name="mail" size={18} /> {t("nav.cta_short")}</a>
          </div>
        </div>
      </div>
    </section>);

}

Object.assign(window, { BusinessCore, BusinessInfra, BusinessFlow, BusinessProducts, BusinessCTA });
