// home-chrome.jsx — Button, top header (badge + centered nav), violet footer.
const { useState, useEffect, useRef } = React;

/* ---------- Button ---------- */
function Button({ children, variant = "line", href, onClick, target, iconRight = false, full = false }) {
  const Tag = href ? "a" : "button";
  const cls = "tl-btn tl-btn--" + variant + (full ? " tl-btn--full" : "");
  return (
    <Tag className={cls} href={href} onClick={onClick}
      target={target} rel={target ? "noreferrer" : undefined}>
      {children}
      {iconRight && <Icon name="arrow" size={16} />}
    </Tag>
  );
}

/* ---------- Top header ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [eduOpen, setEduOpen] = useState(false);
  const [mEdu, setMEdu] = useState(false);
  const closeT = useRef(null);
  const headerRef = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 6);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Publish the sticky header's live height so sub-nav bars (e.g. .ed-tabs)
  // can stick right below it instead of hiding underneath.
  useEffect(() => {
    const el = headerRef.current;
    if (!el) return;
    const setVar = () => document.documentElement.style.setProperty("--tl-header-h", el.offsetHeight + "px");
    setVar();
    const ro = new ResizeObserver(setVar);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const hoverEdu = (v) => {
    clearTimeout(closeT.current);
    if (v) setEduOpen(true);
    else closeT.current = setTimeout(() => setEduOpen(false), 150);
  };

  return (
    <header ref={headerRef} className={"tl-header" + (scrolled ? " is-scrolled" : "")}>
      {/* utility row — centered brand badge + reserve pill */}
      <div className="tl-utility">
        <div className="tl-wrap tl-utility-in">
          <span className="tl-util-spacer"></span>
          <a href="/" className="tl-badge tl-badge--img" aria-label="틴트라이프 5주년">
            <img src="assets/tint-anniversary-logo.png" alt="틴트라이프 5주년 로고" className="tl-badge-logo" />
          </a>
          <div className="tl-util-right">
            <a className="tl-more" href="https://ondayclass.tintlife.co.kr" target="_blank" rel="noreferrer">
              <span>more</span>
              <svg className="tl-more-arrow" width="34" height="10" viewBox="0 0 34 10" fill="none" aria-hidden="true">
                <path d="M0 5H32M32 5L27.5 1M32 5L27.5 9" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </a>
            <button className="tl-mburgerbtn" onClick={() => setOpen(true)} aria-label="메뉴 열기"><Icon name="menu" size={36} /></button>
          </div>
        </div>
      </div>

      {/* nav row */}
      <div className="tl-wrap tl-navbar">
        <nav className="tl-navlinks">
          {NAV.filter((n) => !n.hidden).map((n, i) => n.children ? (
            <div key={n.id} className="tl-nav-edu"
              onMouseEnter={() => hoverEdu(true)} onMouseLeave={() => hoverEdu(false)}>
              {i > 0 && <span className="tl-navsep" aria-hidden="true"></span>}
              <a href={n.href} className={"tl-navlink" + (n.id === (window.ACTIVE_NAV || "home") ? " is-active" : "")}
                target={n.href.startsWith("http") ? "_blank" : undefined} rel={n.href.startsWith("http") ? "noreferrer" : undefined}>
                {n.label}
              </a>
              {eduOpen && (
                <div className="tl-dropdown">
                  {n.children.map((c) => (
                    <a key={c.label} href={c.href} className="tl-dropitem"
                      target={c.href.startsWith("http") ? "_blank" : undefined} rel={c.href.startsWith("http") ? "noreferrer" : undefined}>{c.label}</a>
                  ))}
                </div>
              )}
            </div>
          ) : (
            <React.Fragment key={n.id}>
              {i > 0 && <span className="tl-navsep" aria-hidden="true"></span>}
              <a href={n.href} className={"tl-navlink" + (n.id === (window.ACTIVE_NAV || "home") ? " is-active" : "")}
                target={n.href.startsWith("http") ? "_blank" : undefined}
                rel={n.href.startsWith("http") ? "noreferrer" : undefined}>{n.label}</a>
            </React.Fragment>
          ))}
        </nav>
      </div>

      {open && (
        <div className="tl-drawer-root">
          <div className="tl-drawer-scrim" onClick={() => setOpen(false)}></div>
          <div className="tl-drawer">
            <div className="tl-drawer-top">
              <span className="tl-badge-name" style={{ fontSize: 16 }}>TINTLIFE</span>
              <button onClick={() => setOpen(false)} aria-label="닫기" className="tl-drawer-x"><Icon name="close" /></button>
            </div>
            {NAV.filter((n) => !n.hidden).map((n) => n.children ? (
              <div key={n.id}>
                <button className="tl-mlink" onClick={() => setMEdu(!mEdu)} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", width: "100%" }}>
                  {n.label}<Icon name="chevron" size={15} />
                </button>
                {mEdu && n.children.map((c) => (
                  <a key={c.label} href={c.href} className="tl-mlink tl-mlink--sub"
                    target={c.href.startsWith("http") ? "_blank" : undefined} rel={c.href.startsWith("http") ? "noreferrer" : undefined}>· {c.label}</a>
                ))}
              </div>
            ) : (
              <a key={n.id} href={n.href} className="tl-mlink" onClick={() => setOpen(false)}
                target={n.href.startsWith("http") ? "_blank" : undefined} rel={n.href.startsWith("http") ? "noreferrer" : undefined}>{n.label}</a>
            ))}
            <a className="tl-btn tl-btn--solid tl-btn--full" style={{ marginTop: 18 }} href={CONTACT.review} target="_blank" rel="noreferrer">네이버 예약하기</a>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer({ hideFcta }) {
  const links = NAV.filter((n) => !n.hidden);
  return (
    <React.Fragment>
    {!hideFcta && (
    <section className="tl-fcta" data-screen-label="franchise-cta">
      <div className="tl-fcta-in">
        <p className="tl-fcta-kicker">FRANCHISE</p>
        <h2 className="tl-fcta-title">제2의 직업, 지금 도전하세요.<br /><em>틴트라이프가 함께 합니다.</em></h2>
        <p className="tl-fcta-sub">망설임은 잠시 내려두고, 새로운 라이프스타일을 향한 첫 걸음.<br />일과 삶의 균형, 그 단단한 시작을 틴트라이프가 곁에서 함께 만들어 갑니다.</p>
        <a className="tl-fcta-btn" href="/contact">
          창업 문의하기
          <svg width="22" height="10" viewBox="0 0 22 10" fill="none" aria-hidden="true"><path d="M0 5h20M20 5l-4.2-4M20 5l-4.2 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </a>
      </div>
    </section>
    )}
    <footer className="tl-footer">
      <div className="tl-wrap">
        <nav className="tl-foot-nav">
          {links.map((n) => (
            <a key={n.id} href={n.href} className="tl-foot-link"
              target={n.href.startsWith("http") ? "_blank" : undefined} rel={n.href.startsWith("http") ? "noreferrer" : undefined}>{n.label}</a>
          ))}
          <a href={CONTACT.oneday} className="tl-foot-link" target="_blank" rel="noreferrer">현장체험 교육</a>
        </nav>
        <a href={CONTACT.kakaoChannel} className="tl-foot-kakao" target="_blank" rel="noreferrer">
          <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5c-4 0-7.2 2.55-7.2 5.7 0 2 1.32 3.77 3.32 4.8-.15.53-.53 1.9-.6 2.2-.1.37.14.37.3.27.12-.08 1.9-1.28 2.67-1.8.47.07.96.1 1.51.1 4 0 7.2-2.55 7.2-5.7S12 1.5 8 1.5z" fill="currentColor"/></svg>
          카카오톡 채널 추가
        </a>
        <p className="tl-foot-info">
          상호: {CONTACT.brand} &nbsp;|&nbsp; 본점: {CONTACT.address} &nbsp;|&nbsp; TEL: {CONTACT.tel} (예약/가맹문의) &nbsp;|&nbsp; E-mail: {CONTACT.email}
        </p>
        <p className="tl-foot-copy">사업자등록번호: {CONTACT.bizno} &nbsp;|&nbsp; Copyright © 2020 tintlife. All Rights Reserved</p>
        <p className="tl-foot-copy"><a href="privacy.html" style={{ color: "inherit" }}>개인정보 처리방침</a></p>
      </div>
    </footer>
    </React.Fragment>
  );
}

/* ---------- Scroll-to-top (fixed, bottom-right) ---------- */
function ScrollTop() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <button className={"tl-totop" + (show ? " is-visible" : "")} aria-label="맨 위로"
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
      <img src="assets/btn-top.png" alt="맨 위로" />
    </button>
  );
}

/* ---------- Remote nav (fixed, bottom-right, above scroll-top) ---------- */
function RemoteNav() {
  const [open, setOpen] = React.useState(false);
  const items = [
    { label: "선착순혜택", href: "/startup#special-offer", icon: "gift" },
    { label: "창업문의", href: "/contact", icon: "chat" },
    { label: "원데이클래스", href: "https://ondayclass.tintlife.co.kr/", icon: "info", external: true },
  ];
  const glyph = {
    gift: <path d="M3 8h14v3H3V8zm1 3h12v6H4v-6zm6-3V4m0 0c-1.5-2-4 0-2 1.6.6.5 2 .4 2-1.6zm0 0c1.5-2 4 0 2 1.6-.6.5-2 .4-2-1.6z" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinejoin="round" />,
    chat: <path d="M4 4h12a1 1 0 011 1v8a1 1 0 01-1 1H8l-4 3v-3H4a1 1 0 01-1-1V5a1 1 0 011-1z" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinejoin="round" />,
    info: <g stroke="currentColor" strokeWidth="1.4" fill="none"><circle cx="10" cy="10" r="7.2" /><path d="M10 9v4.5M10 6.4v.1" strokeLinecap="round" /></g>,
  };
  return (
    <div className={"tl-remote" + (open ? " is-open" : "")}>
      {open && (
        <div className="tl-remote-panel" role="menu">
          <div className="tl-remote-head">창업 빠른메뉴</div>
          <div className="tl-remote-rows">
            {items.map((it) => (
              <a key={it.label} className="tl-remote-row" href={it.href}
                target={it.external ? "_blank" : undefined} rel={it.external ? "noreferrer" : undefined}>
                <span className="tl-remote-row-ic">
                  <svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true">{glyph[it.icon]}</svg>
                </span>
                <span className="tl-remote-row-label">{it.label}</span>
                <svg className="tl-remote-row-arrow" width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M5 2l5 5-5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </a>
            ))}
          </div>
        </div>
      )}
      <button className="tl-remote-fab" onClick={() => setOpen((v) => !v)}
        aria-expanded={open} aria-label={open ? "메뉴 닫기" : "창업문의 메뉴 열기"}>
        {open ? (
          <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden="true"><path d="M5 5l12 12M17 5L5 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" /></svg>
        ) : (
          <span className="tl-remote-fab-label" aria-hidden="true">창업<br />문의</span>
        )}
      </button>
    </div>
  );
}

/* ---------- Kakao channel FAB (fixed, bottom-right, below 창업문의) ---------- */
function KakaoFab() {
  return (
    <a className="tl-kakao-fab" href={CONTACT.kakaoChannel} target="_blank" rel="noreferrer" aria-label="카카오 채널 추가">
      <span className="tl-kakao-fab-label">카카오<br />채널<br />추가</span>
    </a>
  );
}

Object.assign(window, { Button, Nav, Footer, ScrollTop, RemoteNav, KakaoFab });
