// ===== Employer demand landing page (M1) =====
// Single entry /lp?type=caregiver|household (D-013, design: M1/lp-unified-design.md).
// No type → caregiver. Legacy /lp/caregiver and /lp/household redirect here
// (edge middleware 308 + client router), keeping UTM parameters. A switch at
// the top of the hero swaps the per-type content in place and keeps the form's
// 需要哪一種協助 in sync.
//
// zh-TW only on purpose: the audience is Taiwanese families reached by
// zh-TW search ads, so copy lives here rather than in hm-i18n-packs.js.
// Submits POST /v1/support/contact with kind=employer_demand (API_GUIDE
// §6.20 v2). Until that endpoint is live the visitor gets the shared
// LeadFallbackCard (mailto prefilled + LINE) instead of a fake success.
//
// Positioning (D-012): Helper321 is the platform. Families leave their needs
// here and the platform refers them to a partner licensed agency, which checks
// eligibility, explains the process and fees, and files the application. Copy
// must never read as if Helper321 itself is the agency ("我們協助…").
//
// Regulatory copy rules (私立就業服務機構許可及管理辦法 §35, 就服法 §5/§40,
// Google Ads Misrepresentation): the partner agency's name, licence number,
// address and phone are disclosed in referral wording (AgencyDisclosure); no
// "保證", no "免費", no promise of eligibility, no implied government
// endorsement. Fact sources are listed in comments next to each page (not
// shown on the page, per D-012).

// TODO(Vincent): fill in before any ad points here. The referral disclosure
// renders only the fields that are set and warns in the console otherwise.
const AGENCY_DISCLOSURE = {
  name: '',      // e.g. 豪幫幫○○有限公司
  licence: '',   // e.g. 勞動部許可證 ○○字第○○○○號
  address: '',
  phone: '',
};

const LP_CITIES = [
  '臺北市', '新北市', '桃園市', '臺中市', '臺南市', '高雄市', '基隆市', '新竹市', '新竹縣',
  '苗栗縣', '彰化縣', '南投縣', '雲林縣', '嘉義市', '嘉義縣', '屏東縣', '宜蘭縣', '花蓮縣',
  '臺東縣', '澎湖縣', '金門縣', '連江縣',
];

const LP_CARE_TYPES = [
  { id: 'household_helper', label: '家庭幫傭（家務、陪伴孩子）', short: '家庭幫傭' },
  { id: 'caregiver', label: '家庭看護（照顧長輩或病人）', short: '家庭看護' },
  { id: 'unsure', label: '還不確定，想先了解', short: '未確定' },
];

const LP_HOUSEHOLD = [
  { id: 'child_under_12', label: '家中有未滿 12 歲的孩子' },
  { id: 'elder_needs_care', label: '家中有長輩需要照顧' },
  { id: 'disabled_member', label: '家中有身心障礙成員' },
  { id: 'dual_income', label: '雙薪家庭' },
];

const LP_TIMELINES = [
  { id: 'within_1_month', label: '1 個月內' },
  { id: '1_3_months', label: '1–3 個月內' },
  { id: '3_plus_months', label: '3 個月以後' },
  { id: 'just_researching', label: '先了解，還沒決定' },
];

const LP_CURRENT_WORKER = [
  { id: 'none', label: '目前沒有聘僱移工' },
  { id: 'replacing', label: '有，想更換' },
  { id: 'adding', label: '有，想再多聘一位' },
];

const LP_CONTACT_PREFS = [
  { id: 'phone', label: '電話' },
  { id: 'line', label: 'LINE' },
  { id: 'email', label: 'Email' },
];

// D-011: required "資格確認狀態". Values are the shared contract with the
// API (Lead.details.eligibility_status, API_GUIDE §6.20) and the growth cost
// sheet's eligibility dimension (T-029). Wording of "confirmed" differs per page.
const LP_ELIGIBILITY_IDS = ['confirmed', 'unsure', 'not_eligible_or_unknown'];
// Short labels for the notification/mailto subject (API_GUIDE §6.20 email rules).
const LP_ELIGIBILITY_SUBJECT = { confirmed: '資格已確認', unsure: '資格不確定', not_eligible_or_unknown: '資格不符或不知道' };
const lpEligibilityOptions = (c) => [
  { id: 'confirmed', label: c.eligibility.confirmedLabel },
  { id: 'unsure', label: '不確定' },
  { id: 'not_eligible_or_unknown', label: '不符合／不知道' },
];

// Four-step flow (T-033, Vincent's wording). Step 2 differs per page.
const lpSteps = (eligibilityStep) => [
  { t: '下方需求表留下需求', d: '填寫下方需求表，大約 1 分鐘。' },
  { t: '確認資格', d: eligibilityStep },
  { t: '協助招募流程', d: '協助準備文件，向勞動部提出申請、協助移工接洽與挑選' },
  { t: '申請聘僱許可、到職', d: '持續協助後續的管理與法定事項。' },
];

const LP_CONTENT = {
  household: {
    sourcePage: 'lp-household',
    defaultCareType: 'household_helper',
    eyebrow: '2026 家庭幫傭新制',
    title: '家裡有未滿 12 歲的孩子，\n現在可以申請外籍家庭幫傭',
    subtitle: '勞動部自 2026 年 4 月 13 日起放寬家庭幫傭資格：家中有未滿 12 歲子女，或有 75 歲以上長輩，點數累計達 4 點即可申請。在 Helper321 留下需求，將有專人協助確認資格並說明流程。',
    // Hero image slot (T-033): Vincent drops the generated image here; spec in PR #48.
    heroImage: '/img/lp-household-hero.jpg',
    eligibility: {
      confirmedLabel: '已確認：點數已確認（達 4 點）',
      help: '新制依家庭成員年齡累計點數，達 4 點便能申請。',
    },
    factsTitle: '新制重點',
    facts: [
      { t: '誰可以申請', d: '家庭成員有未滿 12 歲子女，或有 75 歲以上直系長輩，且依審查標準附表一累計點數達 4 點，即可申請。', icon: 'kids' },
      { t: '幫傭的角色', d: '外籍幫傭是輔助性的家務幫手，來台前須受過家務基本訓練。', icon: 'housework' },
      { t: '每戶 1 名', d: '依審查標準第 14 條，家庭幫傭一戶以聘僱一人為限。', icon: 'role_employer' },
    ],
    steps: lpSteps('依家庭成員年齡計算點數，確認是否達 4 點。'),
    // Sources (not displayed, D-012):
    // - 勞動部新聞稿 2026-03-19 https://www.mol.gov.tw/1607/1632/1633/88489/
    // - 外國人從事就業服務法第四十六條第一項第八款至第十款工作資格及審查標準 第 12、14 條
    //   https://laws.mol.gov.tw/FLAW/FLAWDAT0201.aspx?id=FL028067
  },
  caregiver: {
    sourcePage: 'lp-caregiver',
    defaultCareType: 'caregiver',
    eyebrow: '家庭看護',
    title: '家人需要全天照顧？\n先確認能不能申請外籍看護',
    subtitle: '被看護者符合下列任一條件，就可能可以申請家庭看護工。在 Helper321 留下需求，將有專人依你的情況說明需要準備哪些文件。',
    heroImage: '/img/lp-caregiver-hero.jpg',
    eligibility: {
      confirmedLabel: '已確認：巴氏量表已通過或評估完成',
      help: '被看護者符合上述任一條件，便能申請。',
    },
    factsTitle: '申請資格（符合其一）',
    facts: [
      { t: '80 歲以上', d: '被看護者年滿 80 歲，可免醫療機構評估，持身分證明文件即可申請。', icon: 'elderly' },
      { t: '醫療機構專業評估', d: '未滿 80 歲有全日照護需要，或 80 歲以上有嚴重依賴、85 歲以上有輕度依賴照護需要，經醫療機構評估即可申請。', icon: 'first-aid' },
      { t: '特定身心障礙', d: '被看護者符合審查標準附表二所列的特定身心障礙項目，即可申請。', icon: 'caregiver' },
      { t: '長照服務銜接', d: '符合長照需要等級，且連續使用政府補助的居家、日間或家庭托顧服務滿 6 個月，即可申請。', icon: 'field_calendar' },
    ],
    steps: lpSteps('依年齡、評估結果或身障證明，確認走哪一條申請路徑。'),
    // Sources (not displayed, D-012):
    // - 勞動部新聞稿 2025-07-28 https://www.mol.gov.tw/1607/1632/1633/81743/post
    // - 外國人從事就業服務法第四十六條第一項第八款至第十款工作資格及審查標準 第 18 條
    //   https://laws.mol.gov.tw/FLAW/FLAWDAT0201.aspx?id=FL028067
  },
};

const LP_TYPES = [
  { id: 'caregiver', label: '家庭看護', careType: 'caregiver' },
  { id: 'household', label: '家庭幫傭', careType: 'household_helper' },
];
const LP_DEFAULT_TYPE = 'caregiver';
const lpType = (value) => (LP_TYPES.some(x => x.id === value) ? value : LP_DEFAULT_TYPE);
const lpTypeForCareType = (careType) => (LP_TYPES.find(x => x.careType === careType) || {}).id || null;

// ② Platform-level highlights (shared). Only things the platform actually does;
// no 免費 / 保證 / time or price promises.
const LP_HIGHLIGHTS = [
  { t: '可承接在台移工', d: '已在台灣、依法轉換雇主的移工也能承接，不一定要從國外引進。', icon: 'status_transfer' },
  { t: '先看影片再面談', d: '移工檔案有自我介紹影片，先了解再約面談。', icon: 'field_photo' },
  { t: '由持牌仲介辦理', d: '資格確認與申請，由勞動部許可的合作仲介辦理。', icon: 'field_id' },
];

// ④ In-Taiwan transfer vs overseas recruitment (shared). No day counts: there is
// no official source for typical durations.
const LP_ROUTES = [
  { t: '在台承接', rows: [
    ['說明', '移工已在台灣，依法轉換雇主（例如合約期滿、原雇主同意）'],
    ['適合', '希望盡快開始的家庭'],
    ['備註', '能否承接，依移工的轉換資格和勞動部審核而定'],
  ] },
  { t: '國外引進', rows: [
    ['說明', '由合作仲介從國外招募，移工入境後開始工作'],
    ['適合', '想從更多人選中挑選的家庭'],
    ['備註', '需要的時間通常較長'],
  ] },
];

// ⑦ FAQ (no fee amounts).
const LP_FAQ = [
  { q: '我不確定自己符不符合資格？', a: '留下需求並選「不確定」，合作仲介會依你的家庭狀況確認，最後以勞動部審核為準。' },
  { q: '看護和幫傭有什麼不同？', a: '看護負責照顧被看護者；幫傭是協助家務的幫手。看護不能被要求做全家的家務，否則雇主可能違反就業服務法。' },
  { q: '可以先看看移工嗎？', a: '可以。在 Helper321 瀏覽移工檔案和自我介紹影片，再請合作仲介安排面談。' },
  { q: '送出需求後會發生什麼？', a: 'Helper321 會把需求轉介給合作的持牌仲介，由合作仲介用你選的方式聯絡你、確認資格，並說明流程。' },
  { q: '我的資料會交給誰？', a: '只會提供給 Helper321 的合作仲介，用來聯繫你和說明聘僱流程，詳見隱私權政策第 5 節。' },
];

// Shown after a successful submit.
const LP_NEXT_STEPS = [
  'Helper321 已收到你的需求，後續將安排轉介給合作的持牌仲介',
  '合作仲介會用你選的方式聯絡你，確認資格',
  '確認後，合作仲介說明流程並提供書面報價',
];

// ⑥ Only real, approved, non-demo helpers; the section hides below this many.
const LP_PROFILE_MIN = 6;

// §5 measurement. lp_* events reach dataLayer (→ GA4) only after the visitor
// accepted analytics cookies (D-P1); lead_submit keeps the shared helper.
const lpTrack = (event, params = {}) => {
  try {
    if (localStorage.getItem('hm_cookie_consent') !== 'all') return;
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event, ...params });
  } catch (e) {}
};
const lpUtm = () => {
  try {
    const q = new URLSearchParams(window.location.search);
    return ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
      .reduce((acc, k) => (q.get(k) ? { ...acc, [k]: q.get(k) } : acc), {});
  } catch (e) { return {}; }
};
const lpReplaceTypeInUrl = (type) => {
  try {
    const url = new URL(window.location.href);
    url.searchParams.set('type', type);
    window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);
  } catch (e) {}
};

const lpLabel = (list, id) => (list.find(x => x.id === id) || {}).label || '';

const AgencyDisclosure = () => {
  const d = AGENCY_DISCLOSURE;
  const missing = Object.keys(d).filter(k => !d[k]);
  if (missing.length) {
    try { console.warn('[lp] AGENCY_DISCLOSURE incomplete (私立就業服務機構許可及管理辦法 §35):', missing.join(', ')); } catch (e) {}
  }
  if (!d.name) return null;
  const agency = d.licence ? `${d.name}（${d.licence}）` : d.name;
  const contact = [d.address && `地址：${d.address}`, d.phone && `電話：${d.phone}`].filter(Boolean);
  return (
    <div className="lp-disclosure t-meta" style={{textAlign:'center', color:'var(--t-ink-muted)', lineHeight:1.7}}>
      轉介服務由合作之持牌仲介 {agency} 提供{contact.length ? `　·　${contact.join('　·　')}` : ''}
    </div>
  );
};

// Flat illustrations from flat-icons.jsx (same family as the sign-up role cards).
const LpIcon = ({ name, size = 28 }) => (typeof FlatIcon === 'function' ? <FlatIcon name={name} size={size}/> : null);

// Single hero image (T-033). Until public/img/lp-*-hero.jpg exists the slot shows
// a neutral placeholder, so dropping the file in is the only step to swap it.
const LpHeroImage = ({ src }) => {
  const [failed, setFailed] = useState(false);
  useEffect(() => setFailed(false), [src]);
  return (
    <div className="lp-hero-media" aria-hidden="true">
      {!failed && <img src={src} alt="" loading="eager" decoding="async" onError={() => setFailed(true)}/>}
    </div>
  );
};

// ① Two-segment switch, a native radio group (keyboard: arrows / tab).
// Rendered twice (top of page, eligibility section); `name` keeps the two
// radio groups separate.
const LpTypeSwitch = ({ value, onChange, name = 'lp_type' }) => (
  <div className="lp-switch" role="radiogroup" aria-label="我要找">
    <span className="lp-switch-label" aria-hidden="true">我要找：</span>
    <div className="lp-switch-pill">
      {LP_TYPES.map(o => (
        <label key={o.id} className={`lp-switch-opt${value === o.id ? ' active' : ''}`}>
          <input type="radio" name={name} value={o.id} checked={value === o.id} onChange={() => onChange(o.id)}/>
          <span>{o.label}</span>
        </label>
      ))}
    </div>
  </div>
);

// ⑥ Helper profile preview: real, approved (public API only lists approved),
// non-demo helpers with a photo. Hidden entirely below LP_PROFILE_MIN. No
// "Verified" badge (cross-ai-docs rule).
const LpProfilePreview = ({ go }) => {
  const [helpers, setHelpers] = useState([]);
  useEffect(() => {
    let cancelled = false;
    window.HelperMatchApi?.listCandidates?.({ limit: 50 })
      .then(payload => {
        if (cancelled) return;
        const real = (payload?.data || []).filter(h => h && !h.isDemo && h.photoUrl);
        setHelpers(real.length >= LP_PROFILE_MIN ? real.slice(0, 6) : []);
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);
  if (helpers.length < LP_PROFILE_MIN) return null;
  return (
    <section className="lp-section">
      <div className="container" style={{padding:'0 32px'}}>
        <h2 className="display h-display-sm lp-h2">先看看移工檔案</h2>
        <div className="lp-profiles">
          {helpers.map(h => (
            <button key={h.id} type="button" className="card lp-profile" onClick={() => go(`candidate:${h.slug || h.id}`)}>
              <img src={h.photoUrl} alt="" loading="lazy"/>
              <div className="t-body" style={{fontWeight:700}}>{h.name}</div>
              <div className="t-body-sm" style={{color:'var(--t-ink-soft)'}}>
                {[h.nationality, Number.isFinite(h.yearsExperience) && `經驗 ${h.yearsExperience} 年`].filter(Boolean).join(' · ')}
              </div>
              {h.hasVideo && <div className="t-label lp-profile-video">有自我介紹影片</div>}
            </button>
          ))}
        </div>
        <div style={{textAlign:'center', marginTop:24}}>
          <button type="button" className="btn btn-ghost" onClick={() => go('candidates')}>瀏覽更多移工</button>
        </div>
      </div>
    </section>
  );
};

const LandingPage = ({ initialType, go }) => {
  const [type, setType] = useState(() => lpType(initialType));
  const c = LP_CONTENT[type];
  const { lineUrl } = leadContactChannels();
  // 'form' | 'sending' | 'sent' | 'failed'
  const [state, setState] = useState('form');
  const [error, setError] = useState('');
  const [website, setWebsite] = useState('');
  const emptyForm = () => ({
    name: '', phone: '', lineId: '', email: '', city: '', careType: c.defaultCareType, eligibilityStatus: '',
    household: type === 'household' ? ['child_under_12'] : [],
    startTimeline: '', currentWorker: '', preferredContact: 'phone', contactTime: '',
    message: '', consent: false,
  });
  const [form, setForm] = useState(emptyForm);
  const started = React.useRef(false);
  const set = (k, v) => {
    if (!started.current) { started.current = true; lpTrack('lp_form_start', { lp_type: type }); }
    setForm(f => ({ ...f, [k]: v }));
  };

  useEffect(() => { lpTrack('lp_view', { lp_type: type, ...lpUtm() }); }, []);

  // Either switch → URL (replaceState, keeps UTM), content and the form's care type.
  const switchType = (next, { from = 'switch' } = {}) => {
    const fromForm = from === 'form';
    const t = lpType(next);
    if (t === type) return;
    setType(t);
    lpReplaceTypeInUrl(t);
    lpTrack('lp_type_switch', { lp_type: t, from });
    // Eligibility answers apply only to the selected care type.
    if (!fromForm) setForm(f => ({ ...f, careType: LP_CONTENT[t].defaultCareType, eligibilityStatus: '' }));
  };
  // Form → switches. 還不確定 keeps the current page type.
  const setCareType = (careType) => {
    set('careType', careType);
    if (careType !== form.careType) setForm(f => ({ ...f, eligibilityStatus: '' }));
    const t = lpTypeForCareType(careType);
    if (t) switchType(t, { from: 'form' });
  };
  const toggleHousehold = (id) => setForm(f => ({
    ...f,
    household: f.household.includes(id) ? f.household.filter(x => x !== id) : [...f.household, id],
  }));

  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
  const scrollToForm = () => scrollTo('lp-form');
  const unsureToForm = (e) => {
    e.preventDefault();
    setForm(f => ({ ...f, eligibilityStatus: 'unsure' }));
    scrollToForm();
  };

  // Mobile sticky CTA hides while the form is on screen.
  const [formVisible, setFormVisible] = useState(false);
  useEffect(() => {
    const el = document.getElementById('lp-form');
    if (!el || typeof IntersectionObserver !== 'function') return undefined;
    const io = new IntersectionObserver(([entry]) => setFormVisible(entry.isIntersecting), { threshold: 0.05 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const validate = () => {
    if (!form.name.trim()) return '請填寫稱呼。';
    if (!form.phone.trim() && !form.lineId.trim() && !form.email.trim()) return '電話、LINE ID、Email 請至少填一項，合作仲介才能聯絡你。';
    if (!form.city) return '請選擇縣市。';
    if (!LP_ELIGIBILITY_IDS.includes(form.eligibilityStatus)) return '請選擇資格確認狀態。';
    if (!form.consent) return '請勾選同意，Helper321 才能將需求轉介給合作仲介與你聯絡。';
    return '';
  };

  const submit = async (e) => {
    e.preventDefault();
    const problem = validate();
    setError(problem);
    if (problem) return;
    setState('sending');
    try {
      await window.HelperMatchApi.submitContactForm({
        kind: 'employer_demand',
        name: form.name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        lineId: form.lineId.trim(),
        topic: 'employer',
        message: form.message.trim(),
        consent: form.consent,
        details: {
          care_type: form.careType,
          eligibility_status: form.eligibilityStatus,
          city: form.city,
          household: form.household,
          start_timeline: form.startTimeline || null,
          current_worker: form.currentWorker || null,
          preferred_contact: form.preferredContact,
          contact_time: form.contactTime.trim() || null,
        },
        locale: 'zh-TW',
        sourcePage: c.sourcePage,
        website,
      });
      trackLeadSubmitted('employer_demand', c.sourcePage);
      setState('sent');
    } catch (err) {
      setState('failed');
    }
  };

  const mailto = buildLeadMailto({
    subject: `[Helper321] 雇主需求｜${(LP_CARE_TYPES.find(x => x.id === form.careType) || {}).short || ''}｜${LP_ELIGIBILITY_SUBJECT[form.eligibilityStatus] || ''}｜${form.city}｜${form.name}`,
    lines: [
      `稱呼：${form.name}`,
      form.phone && `電話：${form.phone}`,
      form.lineId && `LINE ID：${form.lineId}`,
      form.email && `Email：${form.email}`,
      `縣市：${form.city}`,
      `需求：${lpLabel(LP_CARE_TYPES, form.careType)}`,
      `資格確認：${lpLabel(lpEligibilityOptions(c), form.eligibilityStatus)}`,
      form.household.length && `家庭狀況：${form.household.map(id => lpLabel(LP_HOUSEHOLD, id)).join('、')}`,
      form.startTimeline && `希望開始：${lpLabel(LP_TIMELINES, form.startTimeline)}`,
      form.currentWorker && `目前移工：${lpLabel(LP_CURRENT_WORKER, form.currentWorker)}`,
      `方便聯絡：${lpLabel(LP_CONTACT_PREFS, form.preferredContact)}${form.contactTime ? `（${form.contactTime}）` : ''}`,
      form.message && `補充：${form.message}`,
      `來源頁：${c.sourcePage}`,
    ],
  });

  const chip = (active) => ({
    display:'flex', alignItems:'center', gap:8, padding:'10px 14px', borderRadius:12, cursor:'pointer',
    border:`1px solid ${active ? 'var(--t-accent)' : 'var(--t-line)'}`,
    background: active ? 'var(--coral-bg)' : 'transparent', fontWeight:500,
  });

  return (
    <div className="page lp-page">
      {/* ① Hero */}
      <section style={{padding:'48px 0 40px', background:'linear-gradient(180deg, var(--t-bg), var(--t-paper))', borderBottom:'1px solid var(--t-line)'}}>
        <div className="container" style={{padding:'0 32px', maxWidth:1080, margin:'0 auto 20px'}}>
          <LpTypeSwitch value={type} onChange={switchType}/>
        </div>
        <div className="container lp-hero" style={{padding:'0 32px', maxWidth:1080, margin:'0 auto'}}>
          <div className="lp-hero-copy">
            <div className="eyebrow">{c.eyebrow}</div>
            <h1 className="display page-title" style={{marginBottom:18, whiteSpace:'pre-line'}}>{c.title}</h1>
            <p className="page-subtitle" style={{maxWidth:620, marginBottom:28}}>{c.subtitle}</p>
            <div className="lp-hero-actions">
              <button className="btn btn-primary btn-lg" onClick={scrollToForm}>留下需求</button>
              <a className="lp-text-link" href="#lp-steps" onClick={e => { e.preventDefault(); scrollTo('lp-steps'); }}>看看怎麼申請 ↓</a>
              {lineUrl && <a className="btn btn-ghost btn-lg" href={lineUrl} target="_blank" rel="noopener noreferrer">LINE 直接問</a>}
            </div>
          </div>
          <LpHeroImage src={c.heroImage}/>
        </div>
      </section>

      {/* ② Highlights (shared) */}
      <section className="lp-section">
        <div className="container" style={{padding:'0 32px'}}>
          <div className="lp-grid">
            {LP_HIGHLIGHTS.map((h, i) => (
              <div key={i} className="card lp-fact" style={{padding:24}}>
                <span className="lp-fact-icon"><LpIcon name={h.icon} size={36}/></span>
                <h3 className="t-body-lg" style={{fontWeight:700, marginBottom:8}}>{h.t}</h3>
                <p className="t-body-sm" style={{lineHeight:1.7, color:'var(--t-ink-soft)'}}>{h.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ③ Eligibility (per type) */}
      <section className="lp-section lp-section-alt">
        <div className="container" style={{padding:'0 32px'}}>
          <h2 className="display h-display-sm lp-h2">{c.factsTitle}</h2>
          <div className="lp-switch-inline">
            <LpTypeSwitch value={type} onChange={t => switchType(t, { from: 'eligibility' })} name="lp_type_eligibility"/>
          </div>
          <div className="lp-grid">
            {c.facts.map((f, i) => (
              <div key={i} className="card lp-fact" style={{padding:24}}>
                <span className="lp-fact-icon"><LpIcon name={f.icon} size={36}/></span>
                <h3 className="t-body-lg" style={{fontWeight:700, marginBottom:8}}>{f.t}</h3>
                <p className="t-body-sm" style={{lineHeight:1.7, color:'var(--t-ink-soft)'}}>{f.d}</p>
              </div>
            ))}
          </div>
          <p className="t-body lp-eligibility-note">
            {c.eligibility.help}<a className="lp-text-link" href="#lp-form" onClick={unsureToForm}>不確定是否符合？留下需求，專人協助您確認 ↓</a>
          </p>
        </div>
      </section>

      {/* ④ In-Taiwan transfer vs overseas recruitment (shared) */}
      <section className="lp-section">
        <div className="container" style={{padding:'0 32px', maxWidth:960, margin:'0 auto'}}>
          <h2 className="display h-display-sm lp-h2">在台承接 vs 國外引進</h2>
          <div className="lp-routes">
            {LP_ROUTES.map(r => (
              <div key={r.t} className="card lp-route" style={{padding:24}}>
                <h3 className="t-body-lg" style={{fontWeight:700, marginBottom:12}}>{r.t}</h3>
                <dl>
                  {r.rows.map(([k, v]) => (
                    <div key={k} className="lp-route-row"><dt>{k}</dt><dd>{v}</dd></div>
                  ))}
                </dl>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ⑤ Steps */}
      <section id="lp-steps" className="lp-section lp-section-alt">
        <div className="container" style={{padding:'0 32px', maxWidth:760, margin:'0 auto'}}>
          <h2 className="display h-display-sm lp-h2">申請流程</h2>
          <ol className="lp-steps">
            {c.steps.map((s, i) => (
              <li key={i} className="lp-step">
                <span className="lp-step-num" aria-hidden="true">{String(i + 1).padStart(2, '0')}</span>
                <div>
                  <div className="t-body" style={{fontWeight:700}}>{s.t}</div>
                  <div className="t-body-sm" style={{color:'var(--t-ink-soft)', lineHeight:1.6}}>{s.d}</div>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* ⑥ Helper profiles (only with ≥ 6 real helpers) */}
      <LpProfilePreview go={go}/>

      {/* ⑦ FAQ */}
      <section className="lp-section">
        <div className="container" style={{padding:'0 32px', maxWidth:760, margin:'0 auto'}}>
          <h2 className="display h-display-sm lp-h2">常見問題</h2>
          <div className="lp-faq">
            {LP_FAQ.map((f, i) => (
              <details key={i} className="card lp-faq-item" onToggle={e => { if (e.currentTarget.open) lpTrack('lp_faq_open', { lp_type: type, faq: i + 1 }); }}>
                <summary className="t-body" style={{fontWeight:700}}>{f.q}</summary>
                <p className="t-body-sm" style={{color:'var(--t-ink-soft)', lineHeight:1.7, marginTop:10}}>{f.a}</p>
              </details>
            ))}
          </div>
        </div>
      </section>

      {/* ⑧ Form */}
      <section id="lp-form" style={{padding:'56px 0 72px', background:'var(--t-paper)', borderTop:'1px solid var(--t-line)'}}>
        <div className="container" style={{padding:'0 32px', maxWidth:720, margin:'0 auto'}}>
          <h2 className="display h-display-sm" style={{textAlign:'center', letterSpacing:'-0.02em', marginBottom:24}}>留下需求</h2>
          <div className="card" style={{padding:32}}>
            {state === 'failed' ? (
              <LeadFallbackCard
                title="線上表單暫時無法送出"
                body="很抱歉，資料沒有送出。請改用 Email 聯絡我們。按下 Email 按鈕，你剛剛填的內容會自動帶入。"
                mailto={mailto}
                emailLabel="用 Email 寄出"
                lineLabel="加 LINE 官方帳號"
                retryLabel="再試一次"
                onRetry={() => setState('form')}
              />
            ) : state === 'sent' ? (
              <div style={{textAlign:'center', padding:'24px 0'}}>
                <div style={{width:56, height:56, borderRadius:99, background:'var(--trust-bg)', color:'var(--trust)', display:'grid', placeItems:'center', margin:'0 auto 18px'}}>
                  <Icon name="check" size={24}/>
                </div>
                <h3 className="display t-heading" style={{marginBottom:18}}>已收到你的需求</h3>
                <div className="t-label" style={{color:'var(--t-ink-muted)', marginBottom:10}}>接下來：</div>
                <ol className="lp-steps lp-next-steps">
                  {LP_NEXT_STEPS.map((step, i) => (
                    <li key={i} className="lp-step">
                      <span className="lp-step-num" aria-hidden="true">{i + 1}</span>
                      <div className="t-body" style={{textAlign:'left', paddingTop:10}}>{step}</div>
                    </li>
                  ))}
                </ol>
                <button type="button" className="btn btn-ghost btn-lg" style={{marginTop:22}} onClick={() => go('candidates')}>先瀏覽移工檔案</button>
              </div>
            ) : (
              <form onSubmit={submit} noValidate style={{position:'relative'}}>
                <LeadHoneypot value={website} onChange={setWebsite}/>
                <div className="lp-form-grid">
                  <div>
                    <label className="label" htmlFor="lp-name">稱呼 *</label>
                    <input id="lp-name" className="input" value={form.name} onChange={e=>set('name', e.target.value)} placeholder="例：王小姐" maxLength={120}/>
                  </div>
                  <div>
                    <label className="label" htmlFor="lp-city">縣市 *</label>
                    <select id="lp-city" className="select" value={form.city} onChange={e=>set('city', e.target.value)}>
                      <option value="">請選擇</option>
                      {LP_CITIES.map(city => <option key={city} value={city}>{city}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="label" htmlFor="lp-phone">手機</label>
                    <input id="lp-phone" className="input" type="tel" inputMode="tel" value={form.phone} onChange={e=>set('phone', e.target.value)} placeholder="09xx-xxx-xxx" maxLength={30}/>
                  </div>
                  <div>
                    <label className="label" htmlFor="lp-line">LINE ID</label>
                    <input id="lp-line" className="input" value={form.lineId} onChange={e=>set('lineId', e.target.value)} maxLength={50}/>
                  </div>
                  <div className="lp-span-2">
                    <label className="label" htmlFor="lp-email">Email</label>
                    <input id="lp-email" className="input" type="email" value={form.email} onChange={e=>set('email', e.target.value)} placeholder="you@example.com"/>
                    <div className="t-label" style={{color:'var(--t-ink-muted)', marginTop:6}}>手機、LINE ID、Email 至少填一項。</div>
                  </div>
                </div>

                <div style={{marginTop:20}}>
                  <div className="label">需要哪一種協助？ *</div>
                  <div style={{display:'flex', flexDirection:'column', gap:8}}>
                    {LP_CARE_TYPES.map(o => (
                      <label key={o.id} style={chip(form.careType === o.id)}>
                        <input type="radio" name="care_type" value={o.id} checked={form.careType === o.id} onChange={()=>setCareType(o.id)}/>
                        {o.label}
                      </label>
                    ))}
                  </div>
                </div>

                <div style={{marginTop:20}} role="radiogroup" aria-labelledby="lp-eligibility-label" aria-describedby="lp-eligibility-help">
                  <div className="label" id="lp-eligibility-label">資格確認狀態 *</div>
                  <div id="lp-eligibility-help" className="t-label" style={{color:'var(--t-ink-muted)', marginBottom:8, lineHeight:1.6}}>{c.eligibility.help}</div>
                  <div style={{display:'flex', flexDirection:'column', gap:8}}>
                    {lpEligibilityOptions(c).map(o => (
                      <label key={o.id} style={chip(form.eligibilityStatus === o.id)}>
                        <input type="radio" name="eligibility_status" value={o.id} checked={form.eligibilityStatus === o.id} onChange={()=>set('eligibilityStatus', o.id)}/>
                        {o.label}
                      </label>
                    ))}
                  </div>
                </div>

                <div style={{marginTop:20}}>
                  <div className="label">家庭狀況（可複選）</div>
                  <div className="lp-form-grid">
                    {LP_HOUSEHOLD.map(o => (
                      <label key={o.id} style={chip(form.household.includes(o.id))}>
                        <input type="checkbox" checked={form.household.includes(o.id)} onChange={()=>toggleHousehold(o.id)}/>
                        {o.label}
                      </label>
                    ))}
                  </div>
                </div>

                <div className="lp-form-grid" style={{marginTop:20}}>
                  <div>
                    <label className="label" htmlFor="lp-timeline">希望何時開始？</label>
                    <select id="lp-timeline" className="select" value={form.startTimeline} onChange={e=>set('startTimeline', e.target.value)}>
                      <option value="">請選擇</option>
                      {LP_TIMELINES.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="label" htmlFor="lp-current">目前是否有聘僱移工？</label>
                    <select id="lp-current" className="select" value={form.currentWorker} onChange={e=>set('currentWorker', e.target.value)}>
                      <option value="">請選擇</option>
                      {LP_CURRENT_WORKER.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
                    </select>
                  </div>
                  <div>
                    <div className="label">希望怎麼聯絡你？</div>
                    <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
                      {LP_CONTACT_PREFS.map(o => (
                        <label key={o.id} style={chip(form.preferredContact === o.id)}>
                          <input type="radio" name="preferred_contact" value={o.id} checked={form.preferredContact === o.id} onChange={()=>set('preferredContact', o.id)}/>
                          {o.label}
                        </label>
                      ))}
                    </div>
                  </div>
                  <div>
                    <label className="label" htmlFor="lp-time">方便聯絡的時段</label>
                    <input id="lp-time" className="input" value={form.contactTime} onChange={e=>set('contactTime', e.target.value)} placeholder="例：平日晚上 7 點後" maxLength={60}/>
                  </div>
                </div>

                <div style={{marginTop:20}}>
                  <label className="label" htmlFor="lp-message">補充說明</label>
                  <textarea id="lp-message" className="input" rows={4} value={form.message} onChange={e=>set('message', e.target.value)} placeholder="例：兩個孩子 3 歲和 7 歲，夫妻都上班" maxLength={4000}/>
                </div>

                <label className="t-body-sm" style={{display:'flex', gap:10, alignItems:'flex-start', marginTop:20, lineHeight:1.6}}>
                  <input type="checkbox" checked={form.consent} onChange={e=>set('consent', e.target.checked)} style={{marginTop:4}}/>
                  <span>我同意 Helper321 的 <a href="/terms" onClick={e=>{ e.preventDefault(); go('terms'); }}>使用條款</a> 與 <a href="/privacy" onClick={e=>{ e.preventDefault(); go('privacy'); }}>隱私權政策</a></span>
                </label>

                {error && <div role="alert" className="t-body-sm" style={{color:'var(--coral-dark)', marginTop:14}}>{error}</div>}

                <button className="btn btn-primary btn-lg" type="submit" disabled={state === 'sending'} style={{width:'100%', marginTop:22}}>
                  {state === 'sending' ? '送出中…' : '送出需求'}
                </button>
              </form>
            )}
          </div>
          <div style={{marginTop:18}}><AgencyDisclosure/></div>
        </div>
      </section>

      {state !== 'sent' && !formVisible && (
        <div className="lp-sticky-cta">
          <button className="btn btn-primary btn-lg" onClick={scrollToForm}>留下需求</button>
        </div>
      )}
    </div>
  );
};
