// =========================================
// 태황 행정사 사무소 — Sections
// =========================================

const { useState, useEffect, useRef } = React;

// ----- Hook: scroll reveal -----
// Progressive enhancement: elements are VISIBLE by default in CSS. We stamp
// [data-pending] only on items offscreen at mount, then IO removes it.
// If IO never fires, a safety timeout clears all pending state.
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const nodes = Array.from(el.querySelectorAll(".reveal"));
    const vh = window.innerHeight;
    const pending = [];
    nodes.forEach((n) => {
      const r = n.getBoundingClientRect();
      if (r.top >= vh * 0.92) {
        n.setAttribute("data-pending", "");
        pending.push(n);
      }
    });
    const clear = (n) => n.removeAttribute("data-pending");

    let io;
    try {
      io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) {
              clear(e.target);
              io.unobserve(e.target);
            }
          });
        },
        { threshold: 0.08, rootMargin: "0px 0px -5% 0px" }
      );
      pending.forEach((n) => io.observe(n));
    } catch (_) { /* fallback covers it */ }

    const t = setTimeout(() => pending.forEach(clear), 1500);
    return () => { if (io) io.disconnect(); clearTimeout(t); };
  }, []);
  return ref;
}

// ----- Navigation -----
function Nav({ active, onNav }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        setScrolled(window.scrollY > 40);
        ticking = false;
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="container row">
        <div className="brand" onClick={() => onNav("top")}>
          <img className="brand-logo" src="assets/logo.svg" alt="태황행정사법인" />
          <div className="brand-text">
            <div className="ko">태황행정사법인</div>
            <div className="en">TaeHwang Licensed Administrative Agent Corp.</div>
          </div>
        </div>
        <div className="nav-links">
          {NAV.map((n) => (
            n.href ? (
              <a key={n.id} className="nav-link" href={n.href}>
                {n.label}
              </a>
            ) : (
              <a
                key={n.id}
                className={"nav-link" + (active === n.id ? " active" : "")}
                onClick={() => onNav(n.id)}
              >
                {n.label}
              </a>
            )
          ))}
        </div>
      </div>
    </nav>
  );
}

// ----- Hero -----
function Hero({ onNav }) {
  const ref = useReveal();
  return (
    <section className="hero" id="top" data-screen-label="01 Hero" ref={ref}>
      <div className="container">
        <div className="hero-grid">
          <div className="hero-copy">
            <div className="eyebrow hero-eyebrow reveal">
              <span className="bar"></span>TAEHWANG LICENSED ADMINISTRATIVE AGENT CORP.
            </div>
            <h1 className="reveal">
              신뢰와 전문성으로<br />
              <span className="accent">함께</span>합니다.
              <span className="divider"></span>
            </h1>
            <p className="lead reveal">
              각종 인·허가부터 개발, 산업단지 조성까지,
              의뢰인의 만족을 넘어 감동에 이르기까지 최선을 다할 것을 약속합니다.
            </p>
            <div className="hero-meta reveal">
              <div className="hm">
                <span className="k">Office</span>
                <span className="v">부산 해운대 · 센텀</span>
              </div>
              <div className="hm">
                <span className="k">Field</span>
                <span className="v">토지 · 건설 행정 전문</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="hero-tag">TAEHWANG · ADMINISTRATIVE</div>
    </section>
  );
}

// ----- About -----
function About() {
  const ref = useReveal();
  return (
    <section className="section about" id="about" data-screen-label="02 About" ref={ref}>
      <div className="container">
        <div className="about-grid">
          <div className="reveal">
            <div className="about-portrait"></div>
            <div className="about-caption">
              <span>代表 行政士</span>
              <span>SEOUL · 02</span>
            </div>
          </div>
          <div className="about-body reveal">
            <div className="eyebrow"><span className="bar"></span>사무소 소개</div>
            <h2 className="serif" style={{
              fontSize: "clamp(36px, 4.2vw, 56px)",
              lineHeight: 1.12,
              letterSpacing: "-0.03em",
              fontWeight: 600,
              margin: "16px 0 32px"
            }}>
              규정과 현장,<br />그 사이의 길을 찾습니다.
            </h2>
            <p>
              <strong>행정사 사무소 태황(太皇)</strong>은 개발 인허가, 행정심판,
              출입국 관리 등 행정 영역 전반의 사건을 다루는 전문 사무소입니다.
              25년 이상의 공직 경험과 600건이 넘는 자문 실적을 토대로,
              서류 한 장이 사업의 향방을 가른다는 사실을 누구보다 잘 알고 있습니다.
            </p>
            <div className="about-quote">
              “복잡한 행정 절차는 결국 사람과 사람,
              그리고 정확한 문서에서 풀린다.”
            </div>
            <p>
              우리는 의뢰인의 사업 일정에 행정 절차를 끼워 맞추지 않습니다.
              <strong>사업의 본질을 먼저 이해하고</strong>, 가장 빠르고 안전한
              인허가 경로를 함께 설계합니다.
            </p>
            <div className="about-sign">
              <div className="about-sign-stamp" style={{
                width: 48, height: 48,
                background: "var(--accent)",
                color: "var(--bg-elevated)",
                display: "grid", placeItems: "center",
                fontFamily: "var(--font-serif)",
                fontSize: 22, fontWeight: 700,
              }}>太</div>
              <div>
                <div className="name">대표 행정사 김 태 황</div>
                <div className="role">PRINCIPAL · KIM TAE-HWANG</div>
              </div>
            </div>
            <div className="credentials">
              {CREDENTIALS.map((c, i) => (
                <div className="credential" key={i}>
                  <span className="year">{c.year}</span>
                  <span>{c.text}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ----- Service detail slide-over panel -----
function ServicePanel({ service, onClose, onContact }) {
  const open = !!service;
  const [mounted, setMounted] = useState(service);
  useEffect(() => {
    if (service) setMounted(service);
  }, [service]);
  const s = service || mounted;
  return (
    <div className={"svc-overlay" + (open ? " open" : "")} onClick={onClose} aria-hidden={!open}>
      <div className="svc-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
        {s && (
          <React.Fragment>
            <button className="svc-close" onClick={onClose} aria-label="닫기">✕</button>
            <div className="svc-modal-head">
              <div className="svc-head-inner">
                <div className="svc-icon"><ServiceIcon name={s.icon} /></div>
                <div className="svc-meta">
                  <div className="svc-num mono">업무 분야 {s.num}</div>
                  <h3 className="serif">{s.title}</h3>
                </div>
              </div>
            </div>
            <div className="svc-body">
              <p className="svc-lede">{s.desc}</p>
              <div className="svc-list-label mono">주요 업무</div>
              <ul className="svc-list">
                {(s.details || []).map((d, i) => (
                  <li key={i}><span className="svc-bullet mono">{String(i + 1).padStart(2, "0")}</span><span>{d}</span></li>
                ))}
              </ul>
              <div className="svc-cta">
                <button className="btn btn-primary" onClick={onContact}>
                  이 업무 상담하기 <span className="arrow">→</span>
                </button>
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// ----- Services -----
function Services() {
  const ref = useReveal();
  const [openIdx, setOpenIdx] = useState(null);
  const active = openIdx != null ? SERVICES[openIdx] : null;

  const onCardClick = (s, i) => {
    if (s.comingSoon) return;
    setOpenIdx(i);
  };

  // lock scroll while panel open
  useEffect(() => {
    document.body.style.overflow = active ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [active]);

  // esc to close
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpenIdx(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const goContact = () => {
    setOpenIdx(null);
    const el = document.getElementById("contact");
    if (el) setTimeout(() => window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 70, behavior: "smooth" }), 120);
  };

  return (
    <section className="section services" id="services" data-screen-label="03 Services" ref={ref}>
      <div className="container">
        <div className="section-head solo reveal">
          <div>
            <div className="eyebrow"><span className="bar"></span>업무 분야</div>
            <h2>다양한 분야의 행정 업무를<br />전문적으로 처리합니다.</h2>
          </div>
        </div>
        <div className="service-grid reveal">
          {SERVICES.map((s, i) => (
            <div
              className={"service-card" + (s.comingSoon ? " is-soon" : " is-clickable")}
              key={s.num}
              onClick={() => onCardClick(s, i)}
            >
              <div className="card-top">
                <div className="card-icon">
                  <ServiceIcon name={s.icon} />
                </div>
                <div className="num">
                  <span>{s.num}</span>
                </div>
              </div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
              {s.comingSoon ? (
                <div className="more more-soon">서비스 준비중 <span className="mono">···</span></div>
              ) : (
                <div className="more">상세 보기 <span className="mono">→</span></div>
              )}
              {s.comingSoon && (
                <div className="soon-overlay">
                  <span className="soon-badge">COMING SOON</span>
                  <span className="soon-text">서비스 준비중입니다</span>
                </div>
              )}
            </div>
          ))}
          <div className="service-card service-card-cta" onClick={goContact}>
            <h3>찾으시는 업무가<br />없으신가요?</h3>
            <p>그 밖의 행정 사무도 폭넓게 자문합니다. 사안을 알려주시면 가능 여부를 안내드립니다.</p>
            <div className="cta-link">상담 문의 <span className="mono">→</span></div>
          </div>
        </div>
      </div>

      <ServicePanel service={active} onClose={() => setOpenIdx(null)} onContact={goContact} />
    </section>
  );
}

// ----- Slogan Band (full-bleed dark) -----
function SloganBand() {
  const ref = useReveal();
  const values = [
    { no: "01", ko: "정확하게", en: "Precision", desc: "법령과 절차를 꼼꼼히 짚어 한 번에 끝냅니다." },
    { no: "02", ko: "빠르게", en: "Speed", desc: "불필요한 단계를 줄여 가장 빠른 길로 안내합니다." },
    { no: "03", ko: "믿음직하게", en: "Trust", desc: "시작부터 끝까지 담당자가 직접 챙깁니다." },
  ];
  return (
    <section className="slogan-band" data-screen-label="Band" ref={ref}>
      <div className="container">
        <div className="band-inner reveal">
          <div className="band-lead">
            <div className="eyebrow"><span className="bar"></span>태황이 일하는 방식</div>
            <h2 className="serif">복잡한 행정도,<br /><span className="accent">쉽고 명확하게.</span></h2>
          </div>
          <div className="band-values">
            {values.map((v, i) => (
              <div className="band-value" key={v.no}>
                <div className="bv-no">{v.no}</div>
                <div className="bv-ko">{v.ko}</div>
                <div className="bv-desc">{v.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ----- Project teaser banner -----
function ProjectTeaser() {
  const ref = useReveal();
  return (
    <section className="proj-teaser" id="projects" data-screen-label="추진 사업" ref={ref}>
      <img className="pt-bg" src="assets/ocean/image3.webp" alt="" aria-hidden="true" />
      <div className="container">
        <div className="pt-inner reveal">
          <div className="eyebrow"><span className="bar"></span>추진 사업 · DEVELOPMENT</div>
          <h2 className="serif">부산 기장<br />최적의 입지시설 분양</h2>
          <p>해안도로에 접한 12,207㎡(3,693평) 부지의 리조트 개발 사업. 인허가부터 단지 조성까지 태황행정사법인이 함께합니다.</p>
          <a className="btn btn-primary" href="projects.html">사업 자세히 보기 <span className="arrow">→</span></a>
        </div>
      </div>
    </section>
  );
}

// ----- Specialty -----
function Specialty() {
  const ref = useReveal();
  return (
    <section className="section specialty" id="specialty" data-screen-label="04 Specialty" ref={ref}>
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="eyebrow"><span className="bar"></span>특화 사업</div>
            <h2>일반 업무 그 너머,<br />복합 사안을 다룹니다.</h2>
          </div>
          <p className="lede">
            여러 부처가 얽힌 복합 인허가, 국공유지 활용, 기각된 처분에 대한
            행정심판 ─ 단일 사무소에서 처리하기 어려운 사안을 전담 팀으로 운영합니다.
          </p>
        </div>
        <div className="specialty-list reveal">
          {SPECIALTIES.map((s) => (
            <div className="specialty-row" key={s.idx}>
              <div className="idx">{s.idx}</div>
              <div className="title serif">{s.title}</div>
              <div className="desc">{s.desc}</div>
              <div className="arrow">VIEW →</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----- Process -----
function Process() {
  const ref = useReveal();
  return (
    <section className="section process" id="process" data-screen-label="05 Process" ref={ref}>
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="eyebrow"><span className="bar"></span>업무 진행 절차</div>
            <h2>네 단계,<br />단 하나의 창구.</h2>
          </div>
          <p className="lede">
            첫 상담부터 결과 통지, 그리고 사후 관리까지 ─
            모든 단계를 담당 행정사가 직접 챙깁니다.
            의뢰인은 한 사람과만 소통하면 됩니다.
          </p>
        </div>
        <div className="process-steps reveal">
          {PROCESS.map((p) => (
            <div className="process-step" key={p.step}>
              <div className="dot">{p.step.replace("STEP ", "")}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--accent)", marginBottom: 8 }}>
                {p.step}
              </div>
              <h4>{p.title}</h4>
              <p>{p.desc}</p>
              <div className="meta">{p.meta}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----- Partner (태황건설) -----
function Partner({ onNav }) {
  const ref = useReveal();
  const p = PARTNER;
  return (
    <section className="section partner-section" id="partner" data-screen-label="06 Partner" ref={ref}>
      <div className="partner-watermark serif" aria-hidden="true">建</div>
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="eyebrow"><span className="bar"></span>협력사 · PARTNER</div>
            <h2>인허가에서 시공까지,<br />하나의 흐름으로.</h2>
          </div>
          <p className="lede">{p.intro}</p>
        </div>

        <div className="partner-grid reveal">
          <div className="partner-id">
            <div className="partner-id-head">
              <div className="partner-id-name serif">{p.name}</div>
              <div className="partner-id-en mono">{p.en}</div>
            </div>
            <table className="profile-table">
              <tbody>
                {p.overview.map((row) => (
                  <tr key={row.label}>
                    <th>{row.label}</th>
                    <td>{row.value}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="partner-detail">
            <div className="partner-block">
              <div className="svc-list-label mono">보유 면허 · 등록</div>
              <ul className="svc-list">
                {p.licenses.map((l, i) => (
                  <li key={i}><span className="svc-bullet mono">{String(i + 1).padStart(2, "0")}</span><span>{l}</span></li>
                ))}
              </ul>
            </div>
            <div className="partner-block">
              <div className="svc-list-label mono">주요 시공 실적</div>
              <ul className="profile-records">
                {p.records.map((r, i) => (
                  <li key={i}>
                    <span className="rec-year mono">{r.year}</span>
                    <span className="rec-title">{r.title}</span>
                    <span className="rec-scale">{r.scale}</span>
                  </li>
                ))}
              </ul>
            </div>
            <p className="profile-note mono">※ 상세 수치 및 등록번호는 실제 자료로 업데이트 예정입니다.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, About, Services, ServicePanel, SloganBand, ProjectTeaser, Specialty, Process, Partner });
