// src/contact.jsx — CONTACT: tier cards, smart floating CTA, anti-sell form modal

function Contact({ onBook }) {
  const c = window.DATA.contact;
  return (
    <section id="contact" className="sec" style={{ borderBottom: 0 }}>
      <div className="wrap">
        <div className="contact-hero">
          <Reveal>
            <h2>
              <RichTitle parts={c.title} />
              {c.title2}
            </h2>
            <p>{c.sub}</p>
          </Reveal>
        </div>

        <Reveal>
          <div className="contact-tiers">
            {c.tiers.map((t, i) => (
              <div className={`tier${t.featured ? " featured" : ""}`} key={i}
                   onClick={() => t.w.includes("重") && onBook()}>
                <div className="w">{t.w}</div>
                <h3>{t.title}</h3>
                <p>{t.desc}</p>
                <div className="lead">{t.lead}</div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// Smart floating CTA — copy adapts to user behavior
function SmartCTA({ onBook }) {
  const [show, setShow] = React.useState(false);
  const [copy, setCopy] = React.useState("查看服务 →");
  const essayReads = React.useRef(new Set());

  React.useEffect(() => {
    let scrollT = null;
    const update = () => {
      const sections = ["home", "about", "thinking", "services", "works"];
      const active = sections.find((id) => {
        const el = document.getElementById(id);
        if (!el) return false;
        const r = el.getBoundingClientRect();
        return r.top < window.innerHeight * 0.4 && r.bottom > window.innerHeight * 0.4;
      });
      const y = window.scrollY;
      // Default: appear after a bit of scrolling
      const shouldShow = y > 600;
      setShow(shouldShow);
      if (active === "thinking") setCopy("订阅观点更新 →");
      else if (active === "services") setCopy("预约咨询 →");
      else if (active === "works") setCopy("看看你的项目可不可以这样做 →");
      else if (active === "about") setCopy("加入读者社群 →");
      else setCopy("查看服务 →");
    };
    const onScroll = () => {
      if (scrollT) cancelAnimationFrame(scrollT);
      scrollT = requestAnimationFrame(update);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    update();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <button className={`smart-cta${show ? " show" : ""}`} onClick={onBook}>
      <span className="dot" />
      <span>{copy}</span>
    </button>
  );
}

// Anti-sales form modal
function BookingModal({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [submitState, setSubmitState] = React.useState("idle");
  const [v, setV] = React.useState({
    name: "", role: "", stage: "", problem: "", budget: "", why: "", email: ""
  });
  const stages = ["创业中（自己的事）", "在职（公司里推动）", "自由顾问 / 自由职业", "投资 / 学术 / 其他"];
  const budgets = ["¥3万 以下", "¥3–10万", "¥10–50万", "¥50万+", "不确定（先聊聊）"];

  React.useEffect(() => {
    if (!open) setTimeout(() => {
      setStep(0);
      setSubmitState("idle");
      setV({ name: "", role: "", stage: "", problem: "", budget: "", why: "", email: "" });
    }, 300);
  }, [open]);

  const submit = async () => {
    if (submitState === "saving") return;
    setSubmitState("saving");
    try {
      const res = await fetch("/api/forms", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ source: "booking-modal", data: v })
      });
      if (!res.ok) throw new Error("submit failed");
      setStep(1);
    } catch (error) {
      const local = JSON.parse(localStorage.getItem("bookingForms") || "[]");
      local.unshift({ id: Date.now(), createdAt: new Date().toISOString(), data: v });
      localStorage.setItem("bookingForms", JSON.stringify(local));
      setStep(1);
    } finally {
      setSubmitState("idle");
    }
  };

  return (
    <div className={`modal-bg${open ? " show" : ""}`} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="close" onClick={onClose}>✕</button>

        {step === 0 ? (
          <>
            <h3>预约 1 对 1 咨询</h3>
            <p className="lead">
              这份表单看起来像在筛人——确实是。我每周接 ≤ 3 场深度咨询，
              所以只能选最对的。请认真作答，每个问题都会被读。
            </p>

            <div className="gate">
              <i>!</i>
              <div>
                提示：把"我想了解一下你"留到面谈，
                这里直接说<strong>你现在卡在哪</strong>——具体的事，具体的人。
              </div>
            </div>

            <div className="field">
              <div className="lbl"><span className="num">01</span> 你目前在做什么？ <span className="hint">单选</span></div>
              <div className="radio-row">
                {stages.map((s) => (
                  <button key={s} className={`radio${v.stage === s ? " on" : ""}`}
                          onClick={() => setV({ ...v, stage: s })}>{s}</button>
                ))}
              </div>
            </div>

            <div className="field">
              <div className="lbl"><span className="num">02</span> 你想解决的问题是什么？ <span className="hint">≥ 80 字</span></div>
              <textarea value={v.problem} onChange={(e) => setV({ ...v, problem: e.target.value })}
                placeholder="举例：我们是一家做 XX 的公司，目前 XX 业务遇到 XX 瓶颈，已经尝试过 XX，效果是 XX..." />
            </div>

            <div className="field">
              <div className="lbl"><span className="num">03</span> 你期望的预算范围 <span className="hint">透明选择</span></div>
              <div className="radio-row">
                {budgets.map((b) => (
                  <button key={b} className={`radio${v.budget === b ? " on" : ""}`}
                          onClick={() => setV({ ...v, budget: b })}>{b}</button>
                ))}
              </div>
            </div>

            <div className="field">
              <div className="lbl"><span className="num">04</span> 为什么选我而不是别人？ <span className="hint">关键问题</span></div>
              <textarea value={v.why} onChange={(e) => setV({ ...v, why: e.target.value })}
                placeholder={`"读过你的 XX 篇文章" / "听 XX 推荐" / "看了 XX 案例" 都可以，但请具体。`} />
            </div>

            <div className="field">
              <div className="lbl"><span className="num">05</span> 联系方式 <span className="hint">邮箱或微信</span></div>
              <input type="text" value={v.email} onChange={(e) => setV({ ...v, email: e.target.value })}
                placeholder="email@example.com 或 wechat_id" />
            </div>

            <button className="submit" onClick={submit} disabled={submitState === "saving"}>
              {submitState === "saving" ? "提交中..." : "提交申请 →"}
            </button>
            <p style={{ fontSize: 11.5, color: "var(--mute)", marginTop: 14, textAlign: "center", lineHeight: 1.7 }}>
              提交后 48 小时内会回复。回答质量是唯一筛选标准——
              不安排回访不代表我们不合适，只代表此刻不合适。
            </p>
          </>
        ) : (
          <>
            <h3 style={{ marginBottom: 16 }}>申请已收到。</h3>
            <p className="lead" style={{ marginBottom: 28 }}>
              我会在 48 小时内亲自读完你的回答。
              如果合适，会给你发一封约时间的邮件——
              不会让助理代劳，因为这一步是我筛选的开始。
            </p>
            <p style={{ padding: 16, background: "var(--accent-soft)", borderRadius: 3, fontSize: 13, lineHeight: 1.7, color: "var(--ink-2)" }}>
              在等回复的这两天，
              你可以读一读我最近写的<a style={{ color: "var(--accent)", borderBottom: "1px solid currentColor" }} href="#thinking" onClick={(e) => { e.preventDefault(); onClose(); document.getElementById("thinking").scrollIntoView({ behavior: "smooth" }); }}>《我为什么拒绝了价值 300 万的"AI 转型"项目》</a>——
              如果你认同里面的判断，那我们大概率会聊得很好。
            </p>
            <button className="submit" onClick={onClose} style={{ background: "var(--ink)", marginTop: 24 }}>关闭</button>
          </>
        )}
      </div>
    </div>
  );
}

function Footer() {
  const follow = window.DATA.footerFollow || {};
  const items = follow.items || [];
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <div className="brand">Sober阿铭</div>
            <p style={{ maxWidth: 320, lineHeight: 1.7 }}>
              实战派 AI 顾问 · 铭文鼎成科技 创始人。<br/>
              把 AI 从概念变成项目，从项目变成收入。
            </p>
          </div>
          <div>
            <h5>导航</h5>
            <ul>
              <li><a href="#home">首页</a></li>
              <li><a href="#about">关于</a></li>
              <li><a href="#thinking">思想</a></li>
              <li><a href="#services">服务</a></li>
              <li><a href="#works">案例</a></li>
            </ul>
          </div>
          <div className="footer-follow">
            <h5>订阅 / 关注</h5>
            {follow.intro && <p className="follow-intro">{follow.intro}</p>}
            <div className="follow-grid">
              {items.map((item, index) => {
                const inner = (
                  <>
                    <div className="follow-media">
                      {item.image ? <img src={item.image} alt={item.title || "订阅二维码"} /> : <span>{item.title || "关注"}</span>}
                    </div>
                    <div className="follow-copy">
                      <strong>{item.title}</strong>
                      <span>{item.desc}</span>
                    </div>
                  </>
                );
                return item.href ? (
                  <a className="follow-card" key={index} href={item.href} target={item.href.startsWith("http") ? "_blank" : undefined} rel="noreferrer">
                    {inner}
                  </a>
                ) : (
                  <div className="follow-card" key={index}>{inner}</div>
                );
              })}
            </div>
          </div>
        </div>
        <div className="colophon">
          <div>© 2026 铭文鼎成科技 · 杭州 · ICP 备案号 2026XXXXXX</div>
          <div className="made">Made with care · v 4.0 · Updated 2026.05.13</div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Contact, SmartCTA, BookingModal, Footer });
