// urlapi.me — SP APP
// Top nav with hamburger, scroll-triggered sticky CTA, Tweaks (hero copy variants).

const { useState: spaUS, useEffect: spaUE } = React;

// ── viewport hook ─────────────────────────────────────
function useIsMobile(breakpoint = 768) {
  const [isM, setIsM] = spaUS(() =>
    typeof window !== "undefined" && window.matchMedia(`(max-width: ${breakpoint}px)`).matches
  );
  spaUE(() => {
    const mq = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const fn = () => setIsM(mq.matches);
    fn();
    if (mq.addEventListener) mq.addEventListener("change", fn);
    else mq.addListener(fn);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener("change", fn);
      else mq.removeListener(fn);
    };
  }, [breakpoint]);
  return isM;
}

// ── tweak defaults (HOST PARSES THIS BLOCK) ───────────
const SP_TWEAKS = /*EDITMODE-BEGIN*/{
  "heroCopy": "asset"
}/*EDITMODE-END*/;

// ── Top Nav with hamburger ────────────────────────────
function SPNav({ onOpenMenu }) {
  const [scrolled, setScrolled] = spaUS(false);
  spaUE(() => {
    const fn = () => setScrolled(window.scrollY > 6);
    fn();
    window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return (
    <nav style={{
      position: "sticky", top: 0, zIndex: 60,
      background: scrolled ? "rgba(6,6,10,0.88)" : "rgba(6,6,10,0.50)",
      backdropFilter: "blur(14px)",
      WebkitBackdropFilter: "blur(14px)",
      borderBottom: scrolled ? "1px solid var(--border)" : "1px solid transparent",
      transition: "background .2s, border-color .2s",
    }}>
      <div style={{
        padding: "10px 14px",
        height: 54,
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <a href="/" style={{ display: "flex", alignItems: "center", gap: 7 }}>
          <img src="/assets/icon.svg" alt="" width="26" height="26" style={{ display: "block" }} />
          <span className="display" style={{ fontSize: 15, fontWeight: 700 }}>
            urlapi<span style={{ color: "var(--accent)" }}>.</span>me
          </span>
          <span className="mono" style={{
            fontSize: 8.5, padding: "1.5px 4px",
            background: "var(--accent-soft)", color: "var(--accent)",
            borderRadius: 3, letterSpacing: 0.08,
          }}>BETA</span>
        </a>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <a href="/app/login.html" style={{
            padding: "7px 8px", fontSize: 12, color: "var(--text-mid)", textDecoration: "none",
          }}>ログイン</a>
          <a href="/app/signup.html" style={{
            padding: "7px 12px",
            background: "linear-gradient(135deg, var(--accent), var(--accent-2))",
            color: "white",
            borderRadius: 6, fontSize: 12, fontWeight: 600,
            display: "inline-flex", alignItems: "center", gap: 4,
            textDecoration: "none",
            boxShadow: "0 0 14px var(--accent-glow)",
          }}>
            無料登録
          </a>
          <button onClick={onOpenMenu} aria-label="メニュー" style={{
            width: 38, height: 38,
            background: "var(--bg-2)",
            border: "1px solid var(--border)",
            borderRadius: 8, color: "var(--text)",
            display: "grid", placeItems: "center", cursor: "pointer",
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M3 7h18M3 12h18M3 17h18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </button>
        </div>
      </div>
    </nav>
  );
}

// ── Hamburger overlay (full-screen) ───────────────────
function SPMenu({ open, onClose }) {
  spaUE(() => {
    if (open) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const links = [
    ["機能",       "#features"],
    ["3つの武器",  "#pillars"],
    ["API / MCP",  "#developer"],
    ["料金",       "#pricing"],
    ["FAQ",        "#faq"],
    ["TQO 白書",   "/tqo"],
    ["Docs",       "/docs/"],
    ["Status",     "/status"],
  ];

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      pointerEvents: open ? "auto" : "none",
      opacity: open ? 1 : 0,
      transition: "opacity .25s ease",
    }}>
      {/* backdrop */}
      <div onClick={onClose} style={{
        position: "absolute", inset: 0,
        background: "rgba(6,6,10,0.78)",
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
      }} />
      {/* drawer */}
      <div style={{
        position: "absolute", top: 0, right: 0, bottom: 0,
        width: "min(86vw, 360px)",
        background: "linear-gradient(180deg, var(--bg-1), var(--bg-0))",
        borderLeft: "1px solid var(--border-strong)",
        padding: "16px 20px 24px",
        display: "flex", flexDirection: "column",
        transform: open ? "translateX(0)" : "translateX(100%)",
        transition: "transform .3s cubic-bezier(.2,.8,.2,1)",
        boxShadow: "-20px 0 60px rgba(0,0,0,0.6)",
      }}>
        {/* header */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          marginBottom: 24,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <img src="/assets/icon.svg" alt="" width="24" height="24" />
            <span className="display" style={{ fontSize: 14, fontWeight: 700 }}>
              urlapi<span style={{ color: "var(--accent)" }}>.</span>me
            </span>
          </div>
          <button onClick={onClose} aria-label="閉じる" style={{
            width: 36, height: 36,
            background: "transparent",
            border: "1px solid var(--border)",
            borderRadius: 8, color: "var(--text)",
            display: "grid", placeItems: "center", cursor: "pointer",
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M6 6l12 12M6 18 18 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </button>
        </div>

        {/* links */}
        <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 2 }}>
          {links.map(([l, h], i) => (
            <li key={l}>
              <a href={h} onClick={onClose} style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "13px 4px",
                fontSize: 16, color: "var(--text)",
                borderBottom: i < links.length - 1 ? "1px solid var(--border-soft)" : "none",
                textDecoration: "none",
              }}>
                <span>{l}</span>
                <I.Right size={14} style={{ color: "var(--text-mute)" }} />
              </a>
            </li>
          ))}
        </ul>

        {/* footer block */}
        <div style={{ flex: 1 }} />

        {/* lang */}
        <div style={{
          display: "flex", background: "var(--bg-2)",
          border: "1px solid var(--border)", borderRadius: 7,
          padding: 3, marginBottom: 12, width: "fit-content",
        }}>
          <a href="/" className="mono" style={{
            padding: "6px 12px", fontSize: 11,
            color: "var(--accent)", background: "var(--accent-soft)",
            borderRadius: 4, textDecoration: "none", letterSpacing: 0.08,
          }}>JP</a>
          <a href="/en/" className="mono" style={{
            padding: "6px 12px", fontSize: 11,
            color: "var(--text-mute)", textDecoration: "none", letterSpacing: 0.08,
          }}>EN</a>
        </div>

        {/* primary CTA */}
        <a href="/app/signup" style={{
          padding: "13px 18px",
          background: "linear-gradient(135deg, var(--accent), var(--accent-2))",
          color: "white",
          borderRadius: 9, fontSize: 14, fontWeight: 700,
          display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
          textDecoration: "none",
          boxShadow: "0 0 20px var(--accent-glow)",
        }}>
          <I.Sparkle size={13} /> 無料ではじめる
        </a>
        <p className="mono" style={{ fontSize: 9.5, color: "var(--text-mute)", marginTop: 14, lineHeight: 1.6 }}>
          © 2026 株式会社9lick.me<br />
          AIで完結する、トラッキング & データ分析。
        </p>
      </div>
    </div>
  );
}

// ── Sticky bottom CTA (appears after scroll) ──────────
function SPStickyCTA() {
  const [show, setShow] = spaUS(false);
  spaUE(() => {
    const fn = () => {
      // show after scrolling 1 viewport, hide near final CTA & footer
      const y = window.scrollY;
      const docH = document.documentElement.scrollHeight;
      const vh = window.innerHeight;
      const nearBottom = y + vh > docH - 360;
      setShow(y > vh * 0.9 && !nearBottom);
    };
    fn();
    window.addEventListener("scroll", fn, { passive: true });
    window.addEventListener("resize", fn);
    return () => {
      window.removeEventListener("scroll", fn);
      window.removeEventListener("resize", fn);
    };
  }, []);
  return (
    <div style={{
      position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 55,
      padding: "10px 14px calc(10px + env(safe-area-inset-bottom))",
      background: "linear-gradient(180deg, rgba(6,6,10,0) 0%, rgba(6,6,10,0.92) 30%)",
      pointerEvents: show ? "auto" : "none",
      transform: show ? "translateY(0)" : "translateY(120%)",
      opacity: show ? 1 : 0,
      transition: "transform .35s cubic-bezier(.2,.8,.2,1), opacity .25s",
    }}>
      <button onClick={() => {
        const el = document.getElementById('signup');
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }} style={{
        width: "100%",
        padding: "14px 18px",
        background: "linear-gradient(135deg, var(--accent), var(--accent-2))",
        border: "1px solid var(--accent-soft)",
        borderRadius: 12,
        color: "white",
        fontSize: 14.5, fontWeight: 700,
        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
        boxShadow: "0 8px 28px rgba(124,92,255,0.45), 0 0 40px var(--accent-glow)",
        cursor: "pointer",
      }}>
        <I.Sparkle size={13} />
        無料ではじめる
        <span className="mono" style={{
          fontSize: 10, padding: "2px 6px",
          background: "rgba(255,255,255,0.18)",
          borderRadius: 4, letterSpacing: 0.06,
          fontWeight: 600,
        }}>FREE</span>
      </button>
    </div>
  );
}

// ── SP Tweaks panel (hero copy only) ──────────────────
function SPTweaks() {
  const [active, setActive] = spaUS(false);
  const [tweaks, setTweaks] = spaUS(SP_TWEAKS);

  spaUE(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setActive(true);
      else if (d.type === '__deactivate_edit_mode') setActive(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // expose to app
  spaUE(() => { window.__SP_TWEAKS = tweaks; window.dispatchEvent(new CustomEvent('sp-tweaks-changed')); }, [tweaks]);

  const set = (k, v) => {
    setTweaks(t => {
      const n = { ...t, [k]: v };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
      return n;
    });
  };

  if (!active) return null;

  const options = [
    { k: "asset", l: "データ資産",   sub: "デフォルト" },
    { k: "ai",    l: "AIに任せろ",   sub: "AI主役" },
    { k: "api",   l: "広告運用を取り戻す", sub: "API主役" },
  ];

  return (
    <div style={{
      position: "fixed", left: 12, right: 12, bottom: 90, zIndex: 90,
      background: "rgba(10,10,18,0.92)",
      border: "1px solid var(--accent-soft)",
      borderRadius: 14, padding: 14,
      backdropFilter: "blur(18px)",
      WebkitBackdropFilter: "blur(18px)",
      boxShadow: "0 16px 48px rgba(0,0,0,0.6), 0 0 30px rgba(124,92,255,0.18)",
      maxWidth: 420, margin: "0 auto",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 10,
      }}>
        <div className="mono" style={{
          fontSize: 10, color: "var(--accent-2)", letterSpacing: 0.18,
          textTransform: "uppercase",
        }}>Tweaks · Hero copy</div>
        <button onClick={() => {
          setActive(false);
          window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
        }} style={{
          width: 24, height: 24,
          background: "transparent",
          border: "1px solid var(--border)",
          borderRadius: 5, color: "var(--text-mid)",
          display: "grid", placeItems: "center", cursor: "pointer",
        }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M6 18 18 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" /></svg>
        </button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {options.map(o => {
          const sel = tweaks.heroCopy === o.k;
          return (
            <button key={o.k} onClick={() => set('heroCopy', o.k)} style={{
              padding: "10px 12px",
              background: sel ? "var(--accent-soft)" : "transparent",
              border: `1px solid ${sel ? "var(--accent)" : "var(--border)"}`,
              borderRadius: 8, color: "var(--text)", cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "space-between",
              textAlign: "left",
            }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{o.l}</div>
                <div className="mono" style={{ fontSize: 9.5, color: "var(--text-mute)", marginTop: 2 }}>{o.sub}</div>
              </div>
              <span style={{
                width: 14, height: 14, borderRadius: 7,
                border: `2px solid ${sel ? "var(--accent)" : "var(--border-strong)"}`,
                background: sel ? "var(--accent)" : "transparent",
                flexShrink: 0,
              }} />
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ── tweak subscription hook ───────────────────────────
function useSPTweaks() {
  const [tweaks, setTweaks] = spaUS(() => window.__SP_TWEAKS || SP_TWEAKS);
  spaUE(() => {
    const fn = () => setTweaks({ ...window.__SP_TWEAKS });
    window.addEventListener('sp-tweaks-changed', fn);
    return () => window.removeEventListener('sp-tweaks-changed', fn);
  }, []);
  return tweaks;
}

// ── SP App (root) ─────────────────────────────────────
function SPApp() {
  const [menuOpen, setMenuOpen] = spaUS(false);
  const tweaks = useSPTweaks();
  // ensure __SP_TWEAKS exists at first render so Hero gets the right copy
  spaUE(() => {
    if (!window.__SP_TWEAKS) window.__SP_TWEAKS = SP_TWEAKS;
  }, []);

  return (
    <>
      <SPNav onOpenMenu={() => setMenuOpen(true)} />
      <SPMenu open={menuOpen} onClose={() => setMenuOpen(false)} />

      <SPHero copy={tweaks.heroCopy || "asset"} />

      {window.AboutTabs && <window.AboutTabs />}

      <div id="pillars"><SPPillars /></div>
      <div id="developer"><SPDeveloper /></div>
      <div id="features"><SPFeatures /></div>
      <SPPricing />
      <div id="faq"><SPFAQ /></div>
      <SPFinalCTA />
      <SPFooter />

      <SPStickyCTA />
      <SPTweaks />
    </>
  );
}

window.SPApp = SPApp;
window.useIsMobile = useIsMobile;
