// Mobile — knowledge index/detail + company + contact (B-option design per design.md)

const M_KN = window.MobileSite;
const S_KN = window.Site;
const PhilosophyK = window.MTopPhilosophy;
const { T: TK, MBtn: BtnK, MPage: PageK, MPageHero: HeroK, MPhoneCTACard: PhoneCardK, MAreaPill: AreaPillK, Img: ImgK, Ic: IcK, MBreadcrumb: BCK } = M_KN;
const { ARTICLES: ART_K, KNOWLEDGE: KNOW_K, COMPANY: CO_K, ASSETS: AS_K, BudouXText: BTK, copyText: copyK, knowledgeCardsFromArticles: buildKnowledgeCardsKM } = S_KN;
const { mobileHref: hrefK, mobileServiceHref: serviceHrefK, mobilePhoneHref: phoneHrefK } = M_KN;

const articleHrefKM = (id) => `${hrefK('knowledge-detail')}&article=${encodeURIComponent(id)}`;
const currentKnowledgeCatM = () => new URLSearchParams(window.location.search).get('cat') || 'すべて';
const knowledgeCatHrefM = (cat) => cat === 'すべて' ? hrefK('knowledge') : `${hrefK('knowledge')}&cat=${encodeURIComponent(cat)}`;

function currentArticleKM() {
  const params = new URLSearchParams(window.location.search);
  const articleId = params.get('article');
  return ART_K.find((x) => x.id === articleId) || ART_K[0];
}

function knowledgeCardsKM() {
  return buildKnowledgeCardsKM(ART_K, KNOW_K);
}

function knowledgeCategoriesKM(cards) {
  return ['すべて'].concat(cards
    .map((k) => k.cat || k.tag)
    .filter((cat, i, arr) => cat && arr.indexOf(cat) === i));
}

// Category tag chip — ベタ塗りをやめ、greenSoft地＋緑文字のライン様式で統一
function MKTag({ children, style }) {
  return (
    <span style={{
      display: 'inline-block', fontSize: 11, color: TK.greenInk, background: TK.greenSoft,
      border: `1px solid ${TK.green}33`,
      padding: '3px 8px', borderRadius: 3, fontWeight: 800, ...style,
    }}>{children}</span>
  );
}

// Orange「読む」action row used in article cards (B-option: orange read affordance)
function MReadRow({ label = '読む' }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      color: TK.oDeep, fontWeight: 800, fontSize: 12.5,
    }}>
      {label}
      <span style={{ width: 18, height: 18, borderRadius: '50%', background: TK.oMain, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
        <IcK.arrow width="11" height="11" color="#fff" />
      </span>
    </span>
  );
}

function MKnowledgeEstimateLink() {
  return (
    <a href={hrefK('contact')} style={{
      display: 'grid', gridTemplateColumns: '34px minmax(0, 1fr) 16px', alignItems: 'center', gap: 10,
      minHeight: 66, padding: '11px 12px', textDecoration: 'none',
      border: `1px solid ${TK.line}`, borderRadius: 9, background: '#fff',
    }}>
      <span aria-hidden="true" style={{
        width: 34, height: 34, borderRadius: 8, background: TK.greenSoft,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <IcK.chat width="19" height="19" color={TK.green} />
      </span>
      <span style={{ display: 'grid', gap: 2, minWidth: 0 }}>
        <span style={{ color: TK.ink, fontSize: 13.5, fontWeight: 800 }}>お見積もりの相談</span>
        <span style={{ color: TK.ink70, fontSize: 11.5, lineHeight: 1.5 }}>気になる箇所やご希望をお聞かせください。</span>
      </span>
      <IcK.arrow width="15" height="15" color={TK.oDeep} />
    </a>
  );
}

// ===== Knowledge index =====
function MPageKnowledgeIndex() {
  const activeCat = currentKnowledgeCatM();
  const cards = knowledgeCardsKM();
  const cats = knowledgeCategoriesKM(cards);
  const visibleArticles = activeCat === 'すべて'
    ? cards
    : cards.filter((k) => k.cat === activeCat || k.tag === activeCat);
  const lead = visibleArticles[0];
  const rest = visibleArticles.slice(1);
  return (
    <PageK active="knowledge">
      <HeroK
        title="住まいの気になること"
        lead="屋根・外壁・雨漏りに関するお役立ち情報を、わかりやすくお届けします。"
      />
      {/* category filter pills — white + 1px line, active = trust green */}
      <section style={{ background: '#fff', padding: '12px 16px', borderBottom: `1px solid ${TK.line}` }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, paddingBottom: 2 }}>
          {cats.map((c) => {
            const isActive = c === activeCat;
            // カテゴリはCMSで自由に増えるため、一部だけアイコンが付くと不揃いに見える。
            // 文字だけで統一する（2026-07-29 しゅんさん指摘）。
            return (
            <a key={c} href={knowledgeCatHrefM(c)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '8px 12px', fontSize: 12.5, fontWeight: 800,
              color: isActive ? '#fff' : TK.ink, background: isActive ? TK.green : '#fff',
              border: isActive ? `1.5px solid ${TK.green}` : `1px solid ${TK.line}`,
              borderRadius: 8, whiteSpace: 'nowrap', textDecoration: 'none',
            }}>
              {c}
            </a>
          )})}
        </div>
      </section>
      {/* featured article — white card, 1px border, orange read affordance */}
      {lead ? (
        <section style={{ background: '#fff', padding: '14px 16px 6px' }}>
          <a href={articleHrefKM(lead.id)} style={{ display: 'block', background: '#fff', border: `1px solid ${TK.line}`, borderRadius: 9, overflow: 'hidden', textDecoration: 'none' }}>
            {/* slot: TEXT-SERVICE-KNOWLEDGE-LEAD (記事画像はARTICLES.photoを使用) */}
            <ImgK src={lead.photo} ratio="3/2" />
            <div style={{ padding: 14 }}>
              <MKTag style={{ marginBottom: 8 }}>{lead.tag}</MKTag>
              <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 18, fontWeight: 700, color: TK.ink, lineHeight: 1.5, marginBottom: 6, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}>{lead.title}</div>
              <div style={{ fontSize: 12.5, color: TK.ink70, lineHeight: 1.9, marginBottom: 8, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}>{lead.lead}</div>
              <MReadRow />
            </div>
          </a>
        </section>
      ) : (
        <section style={{ background: '#fff', padding: '14px 16px 6px' }}>
          <div style={{ border: `1px solid ${TK.line}`, borderRadius: 9, background: '#fff', padding: '18px 14px', textAlign: 'center' }}>
            <p style={{ margin: '0 0 12px', color: TK.ink70, fontSize: 13, lineHeight: 1.8 }}>このカテゴリの記事は現在準備中です。「すべて」から他の記事をご覧ください。</p>
            <a href={hrefK('knowledge')} style={{ color: TK.oDeep, fontWeight: 800, fontSize: 13, textDecoration: 'none', borderBottom: `1.5px solid ${TK.oDeep}`, paddingBottom: 3 }}>すべての記事を見る</a>
          </div>
        </section>
      )}
      {/* article list — white cards, 1px border */}
      <section style={{ background: '#fff', padding: '8px 16px 18px', display: 'grid', gap: 9 }}>
        {rest.map((k) => (
          <a key={k.id} href={articleHrefKM(k.id)} style={{
            display: 'grid', gridTemplateColumns: '104px 1fr', gap: 12,
            padding: 10, textDecoration: 'none',
            border: `1px solid ${TK.line}`, borderRadius: 9, background: '#fff',
          }}>
            <ImgK src={k.photo} ratio="1/1" radius={5} />
            <div style={{ minWidth: 0 }}>
              <MKTag style={{ fontSize: 10.5, marginBottom: 5 }}>{k.tag}</MKTag>
              <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 14, fontWeight: 700, color: TK.ink, lineHeight: 1.5, marginBottom: 4, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}>{k.title}</div>
              <MReadRow />
            </div>
          </a>
        ))}
      </section>
      <section style={{ background: '#fff', padding: '0 16px 10px' }}>
        <MKnowledgeEstimateLink />
      </section>
      <section style={{ background: '#fff', padding: '0 16px 18px' }}>
        <PhoneCardK />
      </section>
    </PageK>
  );
}

// ===== Knowledge detail =====
function MPageKnowledgeDetail() {
  const k = currentArticleKM();
  const paragraphs = k.paragraphs || [];
  const consultations = k.consultations || [];
  // B-option article heading: serif + orange bottom rule
  const h2Style = {
    fontFamily: '"Noto Sans JP", sans-serif', fontSize: 20, fontWeight: 700, color: TK.ink,
    marginTop: 34, lineHeight: 1.5, paddingBottom: 8, borderBottom: `2px solid ${TK.oLine}`,
  };
  return (
    <PageK active="knowledge">
      <section style={{ background: '#fff', padding: '16px 16px 20px', borderBottom: `1px solid ${TK.line}` }}>
        <BCK items={['ホーム', 'お役立ち情報', k.title]} />
        <MKTag style={{ marginTop: 14, marginBottom: 12 }}>{k.tag}</MKTag>
        <h1 style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 26, fontWeight: 700, color: TK.ink, margin: 0, lineHeight: 1.5, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}>{k.title}</h1>
      </section>
      <section style={{ background: '#fff', padding: '20px 16px 24px' }}>
        <ImgK src={k.photo} ratio="16/9" radius={6} />
        <p style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 15, color: TK.ink, lineHeight: 2.2, marginTop: 20 }}>{k.lead}</p>
        <h2 style={h2Style}>{k.bodyTitle || '相談前に知っておきたいこと'}</h2>
        {paragraphs.map((text, i) => (
          <p key={i} style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 14, color: TK.ink80, lineHeight: 2.2, marginTop: 14 }}>
            {text}
          </p>
        ))}
        <div style={{ background: TK.oSoft, color: TK.ink, padding: 16, borderRadius: 9, marginTop: 22 }}>
          <div style={{ fontSize: 12, color: TK.oDeep, fontWeight: 800, marginBottom: 6 }}>ポイント</div>
          <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 14, lineHeight: 2 }}>
            {k.point || '気になることがあれば、無理に判断せず、お電話またはメールでご相談ください。'}
          </div>
        </div>
        <h2 style={h2Style}>よくいただくご相談</h2>
        <ul style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 14, color: TK.ink80, lineHeight: 2.2, marginTop: 12, paddingLeft: 20 }}>
          {consultations.map((item) => <li key={item}>{item}</li>)}
        </ul>
        <div style={{ background: '#fff', border: `1.5px solid ${TK.oLine}`, padding: 16, borderRadius: 9, marginTop: 30 }}>
          <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 16, fontWeight: 700, color: TK.ink, marginBottom: 8 }}>{k.ctaTitle || '住まいの状況を、一度見てほしい方へ'}</div>
          <div style={{ fontSize: 12.5, color: TK.ink70, lineHeight: 1.95, marginBottom: 12 }}>{k.ctaBody || '気になることがあれば、お電話またはメールでお気軽にお問い合わせください。'}</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <BtnK kind="phone" href={phoneHrefK} size="sm" full icon={<IcK.phone width="14" height="14" />}>お電話で相談</BtnK>
            <BtnK kind="email" href={hrefK('contact')} size="sm" full icon={<IcK.chat width="14" height="14" />}>メール</BtnK>
          </div>
        </div>
      </section>
    </PageK>
  );
}

// ===== Company =====
// 2010 local badge (B-option pattern 5) — TOPヒーローのバッジと同一構成。
function MCompany2010Badge({ style }) {
  return (
    <div style={{
      position: 'relative',
      width: 128, height: 128, borderRadius: '50%', background: '#fff',
      border: `2px solid ${TK.heritageGold}`, boxShadow: '0 10px 24px -14px rgba(0,0,0,0.3)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start',
      textAlign: 'center', padding: '15px 12px 0', ...style,
    }}>
      <span style={{ fontSize: 12, fontWeight: 800, color: TK.ink, lineHeight: 1 }}>広島で</span>
      <span style={{ fontWeight: 800, lineHeight: 1, margin: '3px 0 2px', whiteSpace: 'nowrap' }}>
        <span style={{ fontFamily: '"M PLUS 1p", sans-serif', fontSize: 22, letterSpacing: -0.5, color: TK.oMain }}>2010</span>
        <span style={{ fontSize: 11, color: TK.oMain, marginLeft: 1 }}>年</span>
        <span style={{ fontSize: 11, fontWeight: 800, color: TK.ink, marginLeft: 2 }}>から</span>
      </span>
      <span style={{ width: 72, height: 1.5, background: 'rgba(31,111,79,0.55)', margin: '2px 0 3px' }} />
      <span style={{ fontSize: 10, fontWeight: 700, color: TK.ink, lineHeight: 1.4 }}>地域に根ざした<br />施工店</span>
      {/* TOPと同じ値: 絵を円の内側に収めて金リングを切らない（絵の高さ18.8px・下端は円の下端から15px上） */}
      <img src="assets/badge-houses-row-v1.png" alt="" style={{
        position: 'absolute', left: '50%', bottom: 13.45, transform: 'translateX(-50%)',
        width: 80, display: 'block',
        filter: 'drop-shadow(0 1px 0 #fff) drop-shadow(0 -1px 0 #fff) drop-shadow(1px 0 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 0 2px #fff)',
      }} />
    </div>
  );
}

function MPageCompany() {
  // Company overview rows — confirmed items only (社名・住所・電話・設立・受付・対応エリア).
  const { name: licenseNameK, number: licenseNumberK, certifications: certificationsK } = S_KN.licenseContent();
  const certificationRowsK = certificationsK
    .map((certification) => `${certification.name}（${certification.number}）`)
    .join('、');
  const companyAddress = CO_K.address || '広島県広島市西区南観音1-11-17';
  const companyEstablished = CO_K.established || '2010年5月';
  const rows = [
    { icon: IcK.home,  k: '会社名',     v: CO_K.name },
    { icon: IcK.pin,   k: '住所',       v: companyAddress },
    { icon: IcK.phone, k: '電話',       v: CO_K.phone, phone: true },
    { icon: IcK.check, k: '設立',       v: companyEstablished },
    CO_K.hours ? { icon: IcK.clock, k: '受付', v: CO_K.hours } : null,
    { icon: IcK.pin,   k: '対応エリア', v: CO_K.area },
    licenseNameK && licenseNumberK ? {
      icon: IcK.shield, k: '建設業許可',
      v: (
        <>
          <span style={{ display: 'block' }}>{licenseNameK}</span>
          {/* 「（般－5）第40934号」が割れないよう、許可先と番号でまとまりを保つ */}
          {String(licenseNumberK).split(/(?=（)/).map((part, index) => (
            <span key={`${part}-${index}`} style={{ display: 'block', whiteSpace: part.length <= 14 ? 'nowrap' : 'normal' }}>{part}</span>
          ))}
        </>
      ),
    } : null,
    certificationRowsK ? {
      icon: IcK.shield,
      k: '保有資格', // 雨漏り診断士など
      v: certificationRowsK,
    } : null,
  ].filter(Boolean);
  return (
    <PageK active="company">
      <HeroK
        title="会社案内"
        breadcrumb={<>ホーム ／ <span style={{ color: TK.ink }}>会社案内</span></>}
        lead="住まいの修理を、ひとつの窓口で承ります。"
      />
      {/* hero roof photo + 2010 badge re-display */}
      <section style={{ background: '#fff', padding: '14px 16px 28px' }}>
        <div style={{ position: 'relative' }}>
          {/* slot: COMPANY-HERO-IMAGE（青空の屋根写真）。
              以前はTOPと同じ白グラデを重ねていたが、この写真には文字を乗せないため
              可読性の役目がなく、写真が白く霞むだけだった（2026-07-30 しゅんさん指摘で撤去） */}
          <ImgK src={AS_K.heroMain} ratio="16/9" radius={9} />
          <MCompany2010Badge style={{ position: 'absolute', right: 10, bottom: -10 }} />
        </div>
      </section>
      {/* photo gallery — 現場写真3点（モックではヒーロー直下） */}
      <section style={{ background: '#fff', padding: '14px 16px 6px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 9 }}>
          {/* slot: COMPANY-03 / COMPANY-04 / COMPANY-05（現場写真3点） */}
          <ImgK src={AS_K.caseYayamaFlowCheck} ratio="1/1" radius={6} />
          <ImgK src={AS_K.serviceWallReal} ratio="1/1" radius={6} />
          <ImgK src={AS_K.svcMaint} ratio="1/1" radius={6} />
        </div>
      </section>
      {/* 会社概要 — 情報の器なので帯は中立（greenSoft地＋緑文字）。オレンジは押す場所だけに残す */}
      <section style={{ background: '#fff', padding: '14px 16px 6px' }}>
        <div style={{ border: `1px solid ${TK.line}`, borderRadius: 9, overflow: 'hidden', background: '#fff' }}>
          <div style={{ background: TK.greenSoft, color: TK.greenInk, display: 'flex', alignItems: 'center', gap: 8, fontSize: 15, fontWeight: 800, padding: '9px 12px', letterSpacing: 0.3, borderBottom: `1px solid ${TK.line}` }}>
            <IcK.home width="16" height="16" color={TK.green} />
            会社概要
          </div>
          <div>
            {rows.map((r, i) => (
              <div key={r.k} data-mobile-company-row={r.k} style={{
                display: 'grid', gridTemplateColumns: r.k === '住所' ? '22px minmax(0, 1fr)' : '22px 84px minmax(0, 1fr)', gap: 10, alignItems: 'center',
                padding: '11px 12px',
                borderBottom: i < rows.length - 1 ? `1px solid ${TK.line}` : 'none',
              }}>
                <r.icon width="20" height="20" color={TK.green} />
                {r.k === '住所' ? (
                  <div style={{ display: 'grid', gap: 4, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 800, color: TK.ink }}>住所</div>
                    <div style={{ fontSize: 13, color: TK.ink, lineHeight: 1.7, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}>
                      {String(r.v).split(/(\d+丁目\d+-\d+)/).filter(Boolean).map((part, partIndex) => (
                        <React.Fragment key={`${part}-${partIndex}`}>
                          {/\d+丁目\d+-\d+/.test(part) ? <span style={{ whiteSpace: 'nowrap' }}>{part}</span> : part}
                        </React.Fragment>
                      ))}
                    </div>
                  </div>
                ) : (
                  <React.Fragment>
                    <div style={{ fontSize: 12.5, fontWeight: 800, color: TK.ink }}>{r.k}</div>
                    {r.phone ? (
                      <a href={phoneHrefK} style={{ fontFamily: '"M PLUS 1p", "Helvetica Neue", Arial, sans-serif', fontSize: 19, fontWeight: 800, color: TK.oMain, textDecoration: 'none', letterSpacing: 0.3 }}>{r.v}</a>
                    ) : (
                      <div style={{ fontSize: 13, color: TK.ink, lineHeight: 1.7, wordBreak: 'keep-all', overflowWrap: 'anywhere' }}>{r.v}</div>
                    )}
                  </React.Fragment>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>
      {/* trust cards — green line-icon expressions */}
      <section style={{ background: '#fff', padding: '14px 16px 6px', display: 'grid', gridTemplateColumns: '1fr', gap: 9 }}>
        {/* 対応エリアは会社概要の表とヘッダーのピルに出ているため、ここでは繰り返さない（Opusレビュー N6） */}
        <div style={{ border: `1px solid ${TK.line}`, borderRadius: 9, padding: 12, background: '#fff' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <IcK.home width="18" height="18" color={TK.green} />
            <div style={{ fontSize: 13, fontWeight: 800, color: TK.ink, lineHeight: 1.35 }}>住まいの修理を、<br />ひとつの窓口で</div>
          </div>
          <div style={{ fontSize: 11.5, color: TK.ink70, lineHeight: 1.8 }}>
            屋根・外壁・雨漏りなど、住まいの困りごとをまとめてご相談いただけます。
          </div>
        </div>
      </section>
      <section style={{ background: '#fff', padding: '14px 16px 18px' }}>
        <PhoneCardK />
      </section>
      <PhilosophyK />
    </PageK>
  );
}

// ===== Contact =====
// Form input — white, 1px line border, orange border on focus (B-option contact pattern).
function MFormInput({ as = 'input', ...props }) {
  const [focus, setFocus] = React.useState(false);
  const style = {
    width: '100%', boxSizing: 'border-box',
    padding: '12px 14px',
    border: focus ? `1.5px solid ${TK.oLine}` : `1px solid ${TK.line}`,
    borderRadius: 8, outline: 'none',
    fontSize: 14, fontFamily: 'inherit', color: TK.ink, background: '#fff',
    ...(as === 'textarea' ? { resize: 'vertical' } : null),
  };
  const handlers = { onFocus: () => setFocus(true), onBlur: () => setFocus(false) };
  return as === 'textarea'
    ? <textarea {...props} {...handlers} style={style} />
    : <input {...props} {...handlers} style={style} />;
}

function MReqBadge() {
  return <span style={{ fontSize: 10, color: '#fff', background: TK.green, padding: '2px 8px', borderRadius: 4, fontWeight: 800 }}>必須</span>;
}

function MPageContact() {
  const [contactTarget, setContactTarget] = React.useState('roof');
  const [submitStatus, setSubmitStatus] = React.useState('idle');
  const formStartedAtRef = React.useRef(Date.now());
  const privacyHeading = copyK('privacy.contact.heading', '個人情報の取り扱いについて');
  const privacyBodyTemplate = copyK('privacy.contact.body', 'いただいたお名前・ご連絡先・ご相談内容は、お問い合わせへのご回答とご相談内容の確認のためにのみ使用します。ご本人の同意なく第三者へ提供することはありません。取り扱いに関するお問い合わせは、お電話（{電話番号}）またはこのフォームよりご連絡ください。');
  const privacyBody = privacyBodyTemplate.replace(/\{電話番号\}/g, CO_K.phone);
  const fields = [
    { id: 'mobile-contact-name', label: 'お名前', req: true, ph: '例）広島 太郎', type: 'text', name: 'name', autoComplete: 'name' },
    { id: 'mobile-contact-tel', label: '電話番号', req: false, ph: '例）082-xxx-xxxx', type: 'tel', name: 'tel', autoComplete: 'tel' },
    { id: 'mobile-contact-email', label: 'メールアドレス', req: true, ph: '例）example@email.com', type: 'email', name: 'email', autoComplete: 'email' },
  ];
  const targets = [
    { id: 'roof', c: '屋根', Icon: IcK.roof },
    { id: 'wall', c: '外壁', Icon: IcK.brick },
    { id: 'leak', c: '雨漏り', Icon: IcK.drop },
    { id: 'other', c: 'その他', Icon: IcK.home },
  ];
  const submitStatusMessages = {
    sending: '送信中です。そのままお待ちください。',
    sent: '送信しました。内容を確認のうえ、担当者よりご連絡いたします。',
    failed: '送信できませんでした。お手数ですがお電話（082-299-6008）でご連絡ください。',
  };
  const submitStatusMessage = submitStatusMessages[submitStatus];
  const submitButtonStyle = {
    fontFamily: 'inherit', fontWeight: 700, letterSpacing: 0.4,
    fontSize: 14.5, minHeight: 48, padding: '0 18px', cursor: submitStatus === 'sending' ? 'wait' : 'pointer',
    border: 'none', borderRadius: 8, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    width: '100%', whiteSpace: 'nowrap', background: TK.oMain, color: '#fff', opacity: submitStatus === 'sending' ? 0.65 : 1,
  };
  const handleContactSubmit = async (event) => {
    event.preventDefault();
    const form = event.currentTarget;
    setSubmitStatus('sending');

    try {
      const payload = Object.fromEntries(new FormData(form).entries());
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'content-type': 'application/json; charset=utf-8' },
        body: JSON.stringify(payload),
      });
      const data = await response.json().catch(() => null);
      if (!response.ok || !data || data.ok !== true) {
        setSubmitStatus('failed');
        return;
      }
      if (form && typeof form.reset === 'function') form.reset();
      setContactTarget('roof');
      setSubmitStatus('sent');
      formStartedAtRef.current = Date.now();
    } catch (e) {
      setSubmitStatus('failed');
    }
  };
  return (
    <PageK active="contact">
      {/* 説明文は見出し直下に置かず、電話カードの後ろに小さく回す（ファーストビューを電話導線にするため。文言はCMSのまま） */}
      <HeroK title={copyK('cta.title', 'お問い合わせ')} divider={false} />
      {/* phone first — largest phone CTA card at the very top */}
      <section style={{ background: '#fff', padding: '4px 16px 6px' }}>
        <div style={{ textAlign: 'center', fontSize: 13, fontWeight: 800, color: TK.ink, marginBottom: 8 }}>まずはお電話でご相談ください</div>
        <PhoneCardK style={{ padding: '16px 14px 18px' }} />
        <p style={{
          fontFamily: '"Noto Sans JP", sans-serif', fontSize: 12.5, color: TK.ink70, lineHeight: 1.85,
          margin: '12px auto 0', maxWidth: 560, wordBreak: 'auto-phrase', overflowWrap: 'break-word',
        }}>
          <BTK>{`${copyK('cta.lead1', '屋根や外壁、住まいのことで気になることはありませんか？')}${copyK('cta.lead2', '小さなことでも、お電話またはメールフォームよりお気軽にご相談ください。')}`}</BTK>
        </p>
      </section>
      {/* mail form */}
      <section style={{ background: '#fff', padding: '16px 16px 18px' }}>
        <div style={{ border: `1px solid ${TK.line}`, borderRadius: 9, padding: 14, background: '#fff' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, paddingBottom: 10, marginBottom: 14, borderBottom: `1px solid ${TK.line}` }}>
            <IcK.chat width="18" height="18" color={TK.oDeep} />
            <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 17, fontWeight: 800, color: TK.oDeep }}>メールでお問い合わせ</div>
          </div>
          <form onSubmit={handleContactSubmit}>
            <input type="hidden" name="_form" value="mobile-contact" />
            <input type="hidden" name="_page_url" value={window.location.href} />
            <input type="hidden" name="_user_agent" value={navigator.userAgent} />
            <input type="hidden" name="_form_started_at" value={formStartedAtRef.current} />
            <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden' }}>
              <label htmlFor="mobile-contact-website">この欄は入力しないでください</label>
              <input id="mobile-contact-website" name="website" type="text" tabIndex="-1" autoComplete="off" />
            </div>
            {fields.map((f) => (
              <div key={f.id} style={{ display: 'block', marginBottom: 14 }}>
                <label htmlFor={f.id} style={{ fontSize: 12, color: TK.ink, fontWeight: 800, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 8 }}>
                  {f.label}{f.req && <MReqBadge />}
                </label>
                <MFormInput id={f.id} name={f.name} type={f.type} autoComplete={f.autoComplete} required={f.req} placeholder={f.ph} />
              </div>
            ))}

            <div role="radiogroup" aria-labelledby="mobile-contact-target-label" style={{ marginBottom: 14 }}>
              <div id="mobile-contact-target-label" style={{ fontSize: 12, color: TK.ink, fontWeight: 800, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 8 }}>
                気になる箇所 <MReqBadge />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 7 }}>
                {targets.map(({ id, c, Icon }) => (
                  <label key={id} htmlFor={`mobile-contact-target-${id}`} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                    minHeight: 44, padding: '0 4px',
                    border: `1px solid ${contactTarget === id ? TK.oLine : TK.line}`,
                    borderRadius: 8, fontSize: 12, fontWeight: 800,
                    color: TK.ink, cursor: 'pointer', background: contactTarget === id ? TK.oSoft : '#fff', whiteSpace: 'nowrap',
                  }}>
                    <input
                      id={`mobile-contact-target-${id}`}
                      type="radio"
                      name="contact_type"
                      value={id}
                      checked={contactTarget === id}
                      onChange={() => setContactTarget(id)}
                      required
                      style={{ width: 13, height: 13, margin: 0, accentColor: TK.oMain, flexShrink: 0 }}
                    />
                    <Icon width="17" height="17" color={TK.green} style={{ flexShrink: 0 }} />
                    {c}
                  </label>
                ))}
              </div>
            </div>

            <div style={{ display: 'block', marginBottom: 12 }}>
              <label htmlFor="mobile-contact-message" style={{ fontSize: 12, color: TK.ink, fontWeight: 800, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 8 }}>
                ご相談内容 <MReqBadge />
              </label>
              <MFormInput id="mobile-contact-message" name="message" as="textarea" rows={5} required placeholder={'例）天井に茶色のシミが出ています。お住まいの地域もあわせてご記入ください。'} />
            </div>

            <div id="privacy-notice" style={{
              margin: '16px 0 14px',
              padding: '12px 13px',
              borderLeft: `2px solid ${TK.green}`,
              background: TK.greenSoft || '#edf6f1',
              color: TK.ink70,
              fontSize: 11.5,
              lineHeight: 1.85,
              scrollMarginTop: 76,
            }}>
              <div style={{ color: TK.ink, fontWeight: 800, marginBottom: 4 }}>{privacyHeading}</div>
              <div>{privacyBody}</div>
            </div>

            <button type="submit" disabled={submitStatus === 'sending'} style={submitButtonStyle}>
              <IcK.arrow width="16" height="16" /> {submitStatus === 'sending' ? '送信中…' : '送信する'}
            </button>
            {submitStatusMessage && (
              <div role={submitStatus === 'failed' ? 'alert' : 'status'} style={{
                marginTop: 12, padding: '10px 12px', borderRadius: 8, fontSize: 11.5, lineHeight: 1.8,
                color: submitStatus === 'failed' ? TK.oDeep : (TK.greenInk || TK.ink),
                background: submitStatus === 'failed' ? TK.oSoft : (TK.greenSoft || '#edf6f1'),
              }}>
                {submitStatusMessage}
              </div>
            )}
          </form>
        </div>
      </section>
      {/* cases cross-link (mock bottom card) */}
      <section style={{ background: '#fff', padding: '0 16px 18px' }}>
        <a href={hrefK('cases')} style={{
          display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none',
          border: `1.5px solid ${TK.oLine}`, borderRadius: 9, padding: 10, background: '#fff',
        }}>
          {/* slot: CASE-01-AFTER（事例導線サムネイル） */}
          <ImgK src={AS_K.caseYayamaAfter} alt="屋根工事の施工後写真" ratio="1/1" radius={6} style={{ width: 64, flexShrink: 0 }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: TK.oDeep, fontWeight: 800, fontSize: 14 }}>
              <IcK.camera width="16" height="16" color={TK.oDeep} /> 施工事例を見る
            </div>
            <div style={{ fontSize: 11.5, color: TK.ink70, marginTop: 3, lineHeight: 1.7 }}>屋根・外壁の実際の事例をご紹介しています。</div>
          </div>
          <IcK.arrow width="16" height="16" color={TK.oDeep} style={{ flexShrink: 0 }} />
        </a>
      </section>
    </PageK>
  );
}

window.MPageKnowledgeIndex = MPageKnowledgeIndex;
window.MPageKnowledgeDetail = MPageKnowledgeDetail;
window.MPageCompany = MPageCompany;
window.MPageContact = MPageContact;
