// fmp-survey.jsx — FMP Data Coverage Survey Dashboard
// Faithful copy of the FMP "Market Data" dashboard coverage matrix
// (site.financialmodelingprep.com/developer/docs/dashboard?tab=marketData),
// rendered in the proxy site's warm-neutral theme. 263 endpoints across
// 10 categories, with per-plan access (Free / Starter / Premium / Ultimate).
const { useState } = React;

// Per-endpoint access string is 4 chars = [Free, Starter, Premium, Ultimate].
// F = Full Access · L = Limited Access · N = No Access.
const FMP_CATEGORIES = [
  {"title":"Company and Reference Data","groups":[{"sub":"Company Information","eps":[["Company Profile Data","FFFF"],["Company Profile by CIK","FFFF"],["Company Notes","FFFF"],["Stock Peer Comparison","FFFF"],["Delisted Companies","LLFF"],["Company Employee Count","LFFF"],["Company Historical Employee Count","LFFF"],["Company Market Cap","LLLF"],["Batch Market Cap","LLLF"],["Historical Market Cap","LLLF"],["Company Share Float & Liquidity","LLLF"],["All Shares Float","LLLF"],["Latest Mergers & Acquisitions","LFFF"],["Search Mergers & Acquisitions","NNFF"],["Company Executives","LLLF"],["Executive Compensation","LLFF"],["Executive Compensation Benchmark","NNFF"]]},{"sub":"Stock Directory","eps":[["Company Symbols List","NLLF"],["Financial Statement Symbols List","NLLF"],["CIK List","NFFF"],["Symbol Changes List","NFFF"],["ETF Symbol Search","NLLF"],["Actively Trading List","NLLF"],["Earnings Transcript List","NNNF"],["Available Exchanges","NFFF"],["Available Sectors","NFFF"],["Available Industries","NFFF"],["Available Countries","NFFF"]]},{"sub":"Company Search","eps":[["Stock Symbol Search","FFFF"],["Company Name Search","FFFF"],["CIK","FFFF"],["CUSIP","NFFF"],["ISIN","NFFF"],["Stock Screener","NLLF"],["Exchange Variants","NFFF"]]}]},
  {"title":"Fundamental Data","groups":[{"sub":"Financial Statements","eps":[["Income Statement","LLLF"],["Balance Sheet Statement","LLLF"],["Cash Flow Statement","LLLF"],["Latest Financial Statements","NNNF"],["Income Statements TTM","NNNF"],["Balance Sheet Statements TTM","NNNF"],["Cashflow Statements TTM","NNNF"],["Key Metrics","LLLF"],["Financial Ratios","LLLF"],["Key Metrics TTM","LLLF"],["Financial Ratios TTM","LLLF"],["Financial Scores","LLLF"],["Owner Earnings","LLLF"],["Enterprise Values","LLLF"],["Income Statement Growth","LLLF"],["Balance Sheet Statement Growth","LLLF"],["Cashflow Statement Growth","LLLF"],["Financial Statement Growth","LLLF"],["Financial Reports Dates","FFFF"],["Financial Reports Form 10-K JSON","LFFF"],["Financial Reports Form 10-K XLSX","LFFF"],["Revenue Product Segmentation","LLFF"],["Revenue Geographic Segments","LLFF"],["As Reported Income Statements","LFFF"],["As Reported Balance Statements","LFFF"],["As Reported Cashflow Statements","LFFF"],["As Reported Financial Statements","LFFF"]]},{"sub":"Discounted Cash Flow","eps":[["DCF Valuation","LLLF"],["Levered DCF","LLLF"],["Custom DCF Advanced","LLLF"],["Custom DCF Levered","LLLF"]]},{"sub":"SEC Filings","eps":[["Latest 8-K SEC Filings","LFFF"],["Latest SEC Filings","LFFF"],["SEC Filings By Form Type","LFFF"],["SEC Filings By Symbol","LFFF"],["SEC Filings By CIK","LFFF"],["SEC Filings By Name","FFFF"],["SEC Filings Company Search By Symbol","FFFF"],["SEC Filings Company Search By CIK","FFFF"],["SEC Company Full Profile","FFFF"],["Industry Classification List","FFFF"],["Industry Classification Search","NFFF"],["All Industry Classification","NFFF"]]},{"sub":"Fundraisers","eps":[["Latest Crowdfunding Campaigns","FFFF"],["Crowdfunding Campaign Search","FFFF"],["Crowdfunding By CIK","FFFF"],["Equity Offering Updates","FFFF"],["Equity Offering Search","FFFF"],["Equity Offering By CIK","FFFF"]]}]},
  {"title":"Market Data","groups":[{"sub":"Quote","eps":[["Stock Quote","LLLF"],["Stock Quote Short","LLLF"],["Aftermarket Trade","LLLF"],["Aftermarket Quote","LLLF"],["Stock Price Change","LLLF"],["Stock Batch Quote","NNLF"],["Stock Batch Quote Short","NNLF"],["Batch Aftermarket Trade","NNLF"],["Batch Aftermarket Quote","NNLF"],["Exchange Stock Quotes","NNNF"],["Mutual Fund Price Quotes","NNNF"],["ETF Price Quotes","NNNF"],["Full Commodities Quotes","NNNF"],["Full Cryptocurrency Quotes","NNNF"],["Full Forex Quote","NNNF"],["Full Index Quotes","NNNF"]]},{"sub":"Market Performance","eps":[["Market Sector Performance Snapshot","LLLF"],["Industry Performance Snapshot","LLLF"],["Historical Market Sector Performance","LLLF"],["Historical Industry Performance","LLLF"],["Sector PE Snapshot","LLLF"],["Industry PE Snapshot","LLLF"],["Historical Sector PE","LLLF"],["Historical Industry PE","LLLF"],["Biggest Stock Gainers","FFFF"],["Biggest Stock Losers","FFFF"],["Top Traded Stocks","FFFF"]]},{"sub":"Market Hours","eps":[["Global Exchange Market Hours","FFFF"],["Holidays By Exchange","FFFF"],["All Exchange Market Hours","FFFF"]]},{"sub":"Charts","eps":[["Stock Chart Light","LLLF"],["Stock Price and Volume Data","LLLF"],["Unadjusted Stock Price","LLLF"],["Dividend Adjusted Price Chart","LLLF"],["1 Min Interval Stock Chart","NNLF"],["5 Min Interval Stock Chart","NLLF"],["15 Min Interval Stock Chart","NLLF"],["30 Min Interval Stock Chart","NLLF"],["1 Hour Interval Stock Chart","NLLF"],["4 Hour Interval Stock Chart","NLLF"]]}]},
  {"title":"Market News and Calendar","groups":[{"sub":"News","eps":[["FMP Articles","FFFF"],["General News","NLFF"],["Press Releases","NNLF"],["Stock News","NLFF"],["Crypto News","NLFF"],["Forex News","NLFF"],["Search Press Releases","NNLF"],["Search Stock News","NLFF"],["Search Crypto News","NLFF"],["Search Forex News","NLFF"]]},{"sub":"Analyst","eps":[["Financial Estimates","LLLF"],["Ratings Snapshot","LFFF"],["Historical Ratings","LFFF"],["Price Target Summary","LLLF"],["Price Target Consensus","LLLF"],["Stock Grades","LLLF"],["Historical Stock Grades","LLLF"],["Stock Grades Summary","LLLF"]]},{"sub":"Earnings, Dividends, Splits","eps":[["Dividends Company","LLLF"],["Dividends Calendar","LLLF"],["Earnings Report","LLLF"],["Earnings Calendar","LLLF"],["IPOs Calendar","NFFF"],["IPOs Disclosure","NFFF"],["IPOs Prospectus","NFFF"],["Stock Split Details","LLLF"],["Stock Splits Calendar","LLLF"]]}]},
  {"title":"Earnings Call Transcripts","groups":[{"sub":"Earnings Transcript","eps":[["Latest Earning Transcripts","NNNF"],["Earnings Transcript","NNNF"],["Transcripts Dates By Symbol","NNNF"],["Available Transcript Symbols","NNNF"]]}]},
  {"title":"Ownership","groups":[{"sub":"Form 13F","eps":[["Institutional Ownership Filings","NNNF"],["Filings Extract","NNNF"],["Form 13F Filings Dates","NNNF"],["Filings Extract With Analytics By Holder","NNNF"],["Holder Performance Summary","NNNF"],["Holders Industry Breakdown","NNNF"],["Positions Summary","NNNF"],["Industry Performance Summary","NNNF"]]},{"sub":"Senate","eps":[["Latest Senate Financial Disclosures","LFFF"],["Latest House Financial Disclosures","LFFF"],["Senate Trading Activity","NFFF"],["Senate Trades By Name","NFFF"],["U.S. House Trades","NFFF"],["House Trades By Name","NFFF"]]},{"sub":"Insider Trades","eps":[["Latest Insider Trading","LFFF"],["Search Insider Trades","NFFF"],["Search Insider Trades by Reporting Name","NFFF"],["All Insider Transaction Types","FFFF"],["Insider Trade Statistics","NFFF"],["Acquisition Ownership","NFFF"]]}]},
  {"title":"ETF and Mutual Funds","groups":[{"sub":"ETF & Mutual Funds","eps":[["ETF & Fund Holdings","NNNF"],["ETF & Mutual Fund Information","NFFF"],["ETF & Fund Country Allocation","NFFF"],["ETF Asset Exposure","NNNF"],["ETF Sector Weighting","NFFF"],["Mutual Fund & ETF Disclosure","NNNF"],["Mutual Fund Disclosures","NNNF"],["Mutual Fund & ETF Disclosure Name Search","NNNF"],["Fund & ETF Disclosures by Date","NNNF"]]}]},
  {"title":"Advanced Data","groups":[{"sub":"Commitment Of Traders","eps":[["COT Report","NNFF"],["COT Analysis By Dates","NNFF"],["COT Report List","NNFF"]]},{"sub":"Economics","eps":[["Treasury Rates","FFFF"],["Economics Indicators","FFFF"],["Economic Data Releases Calendar","NLFF"],["Market Risk Premium","FFFF"]]},{"sub":"ESG","eps":[["ESG Investment Search","NNNF"],["ESG Ratings","NNNF"],["ESG Benchmark Comparison","NNNF"]]},{"sub":"Technical Indicators","eps":[["Simple Moving Average","NLLF"],["Exponential Moving Average","NLLF"],["Weighted Moving Average","NLLF"],["Double Exponential Moving Average","NLLF"],["Triple Exponential Moving Average","NLLF"],["Relative Strength Index","NLLF"],["Standard Deviation","NLLF"],["Williams","NLLF"],["Average Directional Index","NLLF"]]}]},
  {"title":"Other Markets and Assets","groups":[{"sub":"Indexes","eps":[["Stock Market Indexes List","FFFF"],["Index Quote","LLLF"],["Index Short Quote","LLLF"],["All Index Quotes","NNNF"],["Historical Index Light Chart","LLLF"],["Historical Index Full Chart","LLLF"],["1-Minute Interval Index Price","NNLF"],["5-Minute Interval Index Price","NLLF"],["1-Hour Interval Index Price","NLLF"],["S&P 500 Index","NNFF"],["Nasdaq Index","NNFF"],["Dow Jones","NNFF"],["Historical S&P 500","NNFF"],["Historical Nasdaq","NNFF"],["Historical Dow Jones","NNFF"]]},{"sub":"Commodity","eps":[["Commodities List","FFFF"],["Commodities Quote","LLLF"],["Commodities Quote Short","LLLF"],["All Commodities Quotes","NNNF"],["Light Chart","LLLF"],["Full Chart","LLLF"],["1-Minute Interval Commodities Chart","NNLF"],["5-Minute Interval Commodities Chart","NLLF"],["1-Hour Interval Commodities Chart","NLLF"]]},{"sub":"Crypto","eps":[["Cryptocurrency List","FFFF"],["Full Cryptocurrency Quote","LFFF"],["Cryptocurrency Quote Short","LFFF"],["All Cryptocurrencies Quotes","NNNF"],["Historical Cryptocurrency Light Chart","LFFF"],["Historical Cryptocurrency Full Chart","LFFF"],["1-Minute Interval Cryptocurrency Data","NNFF"],["5-Minute Interval Cryptocurrency Data","NFFF"],["1-Hour Interval Cryptocurrency Data","NFFF"]]},{"sub":"Forex","eps":[["Forex Currency Pairs","FFFF"],["Forex Quote","LFFF"],["Forex Short Quote","LFFF"],["Batch Forex Quotes","NNNF"],["Historical Forex Light Chart","LFFF"],["Historical Forex Full Chart","LFFF"],["1-Minute Interval Forex Chart","NNFF"],["5-Minute Interval Forex Chart","NFFF"],["1-Hour Interval Forex Chart","NFFF"]]}]},
  {"title":"Bulk & Batch Delivery","groups":[{"sub":"Bulk","eps":[["Company Profile Bulk","NNNF"],["Stock Rating Bulk","NNNF"],["DCF Valuations Bulk","NNNF"],["Financial Scores Bulk","NNNF"],["Price Target Summary Bulk","NNNF"],["ETF Holder Bulk","NNNF"],["Upgrades Downgrades Consensus Bulk","NNNF"],["Key Metrics TTM Bulk","NNNF"],["Ratios TTM Bulk","NNNF"],["Stock Peers Bulk","NNNF"],["Earnings Surprises Bulk","NNNF"],["Income Statement Bulk","NNNF"],["Income Statement Growth Bulk","NNNF"],["Balance Sheet Statement Bulk","NNNF"],["Balance Sheet Statement Growth Bulk","NNNF"],["Cash Flow Statement Bulk","NNNF"],["Cash Flow Statement Growth Bulk","NNNF"],["Eod Bulk","NNNF"]]}]}
];

const PLAN_KEYS = ["Free", "Starter", "Premium", "Ultimate"];
const TOTAL_ENDPOINTS = FMP_CATEGORIES.reduce(
  (n, c) => n + c.groups.reduce((m, g) => m + g.eps.length, 0), 0
);

// chip style by access char for the active plan
function chipStyle(ch) {
  if (ch === "F") {
    return { background: "var(--accent)", color: "var(--ink-inverse)", borderColor: "var(--accent)" };
  } else if (ch === "L") {
    return { background: "var(--warn-soft)", color: "var(--warn)", borderColor: "var(--warn)" };
  }
  return { background: "var(--bg-sunken)", color: "var(--ink-soft)", borderColor: "var(--rule)" };
}

function dotColor(ch) {
  return ch === "F" ? "var(--accent)" : ch === "L" ? "var(--warn)" : "var(--ink-soft)";
}

function FmpSurveyBody() {
  const [planIdx, setPlanIdx] = useState(1); // default Starter
  const [collapsed, setCollapsed] = useState({}); // category title -> bool

  // survey form state
  const [email, setEmail] = useState("");
  const [comments, setComments] = useState("");
  const [checkedInterests, setCheckedInterests] = useState({
    company: false, fundamentals: true, marketdata: true, news: false,
    transcripts: false, ownership: false, etf: false, advanced: false,
    othermarkets: false, bulk: false
  });
  const [loading, setLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");

  const selectedPlan = PLAN_KEYS[planIdx];

  const toggleCat = (title) => setCollapsed(prev => ({ ...prev, [title]: !prev[title] }));
  const handleCheckboxChange = (key) =>
    setCheckedInterests(prev => ({ ...prev, [key]: !prev[key] }));

  // counts for the active plan, used in the summary chip
  const planCounts = (() => {
    let f = 0, l = 0, n = 0;
    FMP_CATEGORIES.forEach(c => c.groups.forEach(g => g.eps.forEach(([, acc]) => {
      const ch = acc[planIdx];
      if (ch === "F") f++; else if (ch === "L") l++; else n++;
    })));
    return { f, l, n };
  })();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErrorMsg("");
    const interests = Object.keys(checkedInterests).filter(k => checkedInterests[k]);
    try {
      const response = await fetch('/api/survey/fmp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, tier: selectedPlan, interests, comments })
      });
      const data = await response.json();
      if (data.success) setSubmitted(true);
      else setErrorMsg(data.message || "Failed to submit survey.");
    } catch (err) {
      console.error(err);
      setErrorMsg("Network error. Please try again later.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto" }}>
      {/* --- Title & Intro --- */}
      <div className="eyebrow" style={{ marginBottom: 10 }}>FMP Integration Survey · 问卷与功能看板</div>
      <h2 className="display-title" style={{ fontSize: 38, margin: "0 0 8px" }}>FMP Market Data Coverage</h2>
      <p style={{ fontSize: 15, color: "var(--ink-muted)", margin: "0 0 6px" }}>
        We are planning to proxy the full Financial Modeling Prep (FMP) <code style={{ fontFamily: "var(--f-mono)", fontSize: 13 }}>/stable/*</code> catalogue —
        all <strong style={{ color: "var(--ink-strong)" }}>{TOTAL_ENDPOINTS}</strong> endpoints across {FMP_CATEGORIES.length} categories.
        Pick a plan to see exactly what each tier unlocks, then tell us which data you need at the bottom.
      </p>
      <p style={{ fontSize: 13, color: "var(--ink-soft)", margin: "0 0 24px" }}>
        我们计划把 FMP 全量 <code style={{ fontFamily: "var(--f-mono)" }}>/stable/*</code> 接口（共 {TOTAL_ENDPOINTS} 个端点、{FMP_CATEGORIES.length} 大类）接入代理。
        在下方选择套餐即可查看每个层级解锁的具体数据范围，并在页面底部告诉我们您最需要哪些接口。
      </p>

      {/* --- Plan Selector --- */}
      <div style={{
        display: "flex", justifyContent: "center", background: "var(--bg-sunken)",
        borderRadius: "var(--radius-lg)", padding: 4, marginBottom: 20,
        border: "1px solid var(--rule-strong)"
      }}>
        {PLAN_KEYS.map((p, i) => (
          <button
            key={p}
            onClick={() => setPlanIdx(i)}
            style={{
              flex: 1, padding: "10px 16px", fontFamily: "var(--f-sans)", fontSize: 14,
              fontWeight: planIdx === i ? 600 : 500, border: "none",
              borderRadius: "var(--radius-md)", cursor: "pointer",
              background: planIdx === i ? "var(--bg-paper)" : "transparent",
              color: planIdx === i ? "var(--ink-strong)" : "var(--ink-muted)",
              boxShadow: planIdx === i ? "0 1px 3px rgba(0,0,0,0.06)" : "none",
              transition: "all 0.15s ease"
            }}
          >
            {p}
          </button>
        ))}
      </div>

      {/* --- Legend + active-plan summary --- */}
      <div style={{
        display: "flex", justifyContent: "center", alignItems: "center", gap: 24,
        fontSize: 12.5, color: "var(--ink-muted)", marginBottom: 28,
        fontFamily: "var(--f-mono)", flexWrap: "wrap"
      }}>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--accent)" }}/>
          Full Access · 完整访问 <strong style={{ color: "var(--ink-strong)" }}>({planCounts.f})</strong>
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--warn)", border: "1px solid var(--warn)" }}/>
          Limited Access · 受限访问 <strong style={{ color: "var(--ink-strong)" }}>({planCounts.l})</strong>
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--bg-sunken)", border: "1px solid var(--ink-soft)" }}/>
          No Access · 无权限 <strong style={{ color: "var(--ink-strong)" }}>({planCounts.n})</strong>
        </span>
      </div>

      {/* --- Category cards --- */}
      <div style={{ display: "flex", flexDirection: "column", gap: 16, marginBottom: 44 }}>
        {FMP_CATEGORIES.map((cat) => {
          const isCollapsed = !!collapsed[cat.title];
          // category-level dot summary for active plan
          const counts = { F: 0, L: 0, N: 0 };
          cat.groups.forEach(g => g.eps.forEach(([, acc]) => { counts[acc[planIdx]]++; }));
          const total = counts.F + counts.L + counts.N;

          return (
            <div key={cat.title} className="card" style={{ padding: 0, background: "var(--bg-paper)", overflow: "hidden" }}>
              {/* Category header (clickable to collapse) */}
              <div
                onClick={() => toggleCat(cat.title)}
                style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: "16px 22px", cursor: "pointer", userSelect: "none",
                  borderBottom: isCollapsed ? "none" : "1px solid var(--rule-faint)"
                }}
              >
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <span style={{
                    display: "inline-block", transition: "transform 0.15s ease",
                    transform: isCollapsed ? "rotate(-90deg)" : "rotate(0deg)",
                    color: "var(--ink-soft)", fontSize: 12
                  }}>▼</span>
                  <h3 className="display-title" style={{ fontSize: 19, margin: 0, color: "var(--ink-strong)" }}>
                    {cat.title}
                  </h3>
                  <span style={{ fontFamily: "var(--f-mono)", fontSize: 11, color: "var(--ink-soft)" }}>
                    {total} endpoints
                  </span>
                </div>
                <div style={{ display: "flex", gap: 14, fontFamily: "var(--f-mono)", fontSize: 11.5, color: "var(--ink-muted)" }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                    <span style={{ width: 7, height: 7, borderRadius: "50%", background: dotColor("F") }}/>{counts.F}
                  </span>
                  <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                    <span style={{ width: 7, height: 7, borderRadius: "50%", background: dotColor("L") }}/>{counts.L}
                  </span>
                  <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                    <span style={{ width: 7, height: 7, borderRadius: "50%", background: dotColor("N") }}/>{counts.N}
                  </span>
                </div>
              </div>

              {/* Subsections */}
              {!isCollapsed && (
                <div style={{ padding: "8px 22px 22px" }}>
                  {cat.groups.map((g) => (
                    <div key={g.sub} style={{ marginTop: 18 }}>
                      <h4 style={{
                        fontFamily: "var(--f-sans)", fontSize: 13, fontWeight: 600,
                        textTransform: "uppercase", letterSpacing: ".05em",
                        color: "var(--ink-muted)", margin: "0 0 12px"
                      }}>
                        {g.sub}
                      </h4>
                      <div style={{
                        display: "grid",
                        gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))",
                        gap: 8
                      }}>
                        {g.eps.map(([name, acc]) => (
                          <div
                            key={name}
                            title={name}
                            style={{
                              padding: "9px 12px", borderRadius: "var(--radius-md)",
                              border: "1px solid", fontSize: 12, fontWeight: 500,
                              textAlign: "center", display: "flex", alignItems: "center",
                              justifyContent: "center", lineHeight: 1.25,
                              ...chipStyle(acc[planIdx])
                            }}
                          >
                            {name}
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* --- Survey Form Card --- */}
      <div id="fmp-survey-form" className="card" style={{ padding: "32px 40px", background: "var(--bg-paper)", border: "1px solid var(--rule-strong)", boxShadow: "0 4px 12px rgba(0,0,0,0.02)" }}>
        {!submitted ? (
          <form onSubmit={handleSubmit}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Survey · 反馈调研</div>
            <h3 className="display-title" style={{ fontSize: 26, margin: "0 0 12px" }}>
              Which FMP data should we add first?
            </h3>
            <p style={{ fontSize: 14, color: "var(--ink-muted)", margin: "0 0 24px" }}>
              You're viewing the <strong style={{ color: "var(--ink-strong)" }}>{selectedPlan}</strong> tier.
              Tick the categories you need and submit — this tells us which {TOTAL_ENDPOINTS} endpoints to prioritise.
              <br/>
              <span style={{ color: "var(--ink-soft)", fontSize: 12.5 }}>
                您正在查看 <strong style={{ color: "var(--ink-strong)" }}>{selectedPlan}</strong> 套餐。勾选您需要的分类并提交，帮助我们决定优先接入哪些端点。
              </span>
            </p>

            <div style={{ display: "flex", flexDirection: "column", gap: 18, marginBottom: 24 }}>
              <div>
                <label className="label">Which categories do you need most? (您最需要哪些数据分类？)</label>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 8 }}>
                  {[
                    ["company", "Company & Reference (公司与参考数据)"],
                    ["fundamentals", "Fundamentals & Statements (财报与基本面)"],
                    ["marketdata", "Market Data: Quotes & Charts (行情与K线)"],
                    ["news", "News & Calendar (新闻与日历)"],
                    ["transcripts", "Earnings Call Transcripts (会议纪要文本)"],
                    ["ownership", "Ownership: 13F / Senate / Insider (持仓与内部交易)"],
                    ["etf", "ETF & Mutual Funds (ETF 与基金)"],
                    ["advanced", "Advanced: COT / Econ / ESG / Technicals (高级数据)"],
                    ["othermarkets", "Indexes / Commodity / Crypto / Forex (其他市场)"],
                    ["bulk", "Bulk & Batch Delivery (批量下载)"]
                  ].map(([key, label]) => (
                    <label key={key} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, cursor: "pointer" }}>
                      <input type="checkbox" checked={checkedInterests[key]} onChange={() => handleCheckboxChange(key)} style={{ accentColor: "var(--accent)" }} />
                      {label}
                    </label>
                  ))}
                </div>
              </div>

              <div>
                <label className="label">Your Email (您的邮箱 - 选填，以便有进展时通知您)</label>
                <input
                  type="email" className="input mono" placeholder="developer@example.com"
                  value={email} onChange={e => setEmail(e.target.value)}
                />
              </div>

              <div>
                <label className="label">Any specific endpoint or use-case? (您的具体接口需求或使用场景？)</label>
                <textarea
                  className="input" style={{ minHeight: 80, resize: "vertical" }}
                  placeholder="E.g., I need 1-min interval stock charts + bulk EOD for backtesting..."
                  value={comments} onChange={e => setComments(e.target.value)}
                />
              </div>
            </div>

            {errorMsg && (
              <div style={{ color: "var(--danger)", background: "var(--danger-soft)", border: "1px solid var(--danger)", padding: "10px 12px", borderRadius: 4, fontSize: 13, marginBottom: 16 }}>
                {errorMsg}
              </div>
            )}

            <button
              type="submit" className="btn primary"
              style={{ width: "100%", justifyContent: "center", padding: "12px 16px", fontSize: 14 }}
              disabled={loading}
            >
              {loading ? "Submitting..." : `Submit Survey: I'm interested in FMP ${selectedPlan} →`}
            </button>
          </form>
        ) : (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <span style={{
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              width: 48, height: 48, borderRadius: "50%", background: "var(--ok-soft)",
              color: "var(--ok)", fontSize: 24, marginBottom: 16
            }}>✓</span>
            <h3 className="display-title" style={{ fontSize: 26, margin: "0 0 8px" }}>
              Thank You! (谢谢您的参与！)
            </h3>
            <p style={{ fontSize: 14, color: "var(--ink-muted)", margin: "0 0 20px", maxWidth: 440, marginLeft: "auto", marginRight: "auto" }}>
              Your interest in the <strong style={{ color: "var(--ink-strong)" }}>{selectedPlan}</strong> tier has been recorded. This feedback helps us prioritize our next features.
              <br/>
              <span style={{ color: "var(--ink-soft)", fontSize: 12.5 }}>
                我们已成功记录您对 <strong style={{ color: "var(--ink-strong)" }}>{selectedPlan}</strong> 方案的兴趣。您的建议将直接帮助我们规划未来的代理接口集成！
              </span>
            </p>
            <button className="btn" onClick={() => setSubmitted(false)} style={{ fontSize: 12.5 }}>
              ← Submit another response
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

window.FmpSurveyBody = FmpSurveyBody;
