// Mobile — services index + detail, cases index + detail
// B-option (design.md): white surface / orange wayfinding / green line icons / proof photos.

const M_SC = window.MobileSite;
const S_SC = window.Site;
const { T: TS, MPage: PageS, MPageHero: HeroS, MSectionHeading: SHS, MPhoneCTACard: PhoneCardS, Img: ImgS, Ic: IcS } = M_SC;
const { COMPANY: CO_S, SERVICES: SV_S, FLOW_STEPS: FLOW_S, CASES: CASES_S, BudouXText: BTS, FLOW_NO_BREAK: FLOW_NO_BREAK_S, rawCopyValue: rawCopyS, hasText: hasTextS, hasImageRef: hasImageRefS } = S_SC;
const { mobileHref: hrefS, mobileServiceHref: serviceHrefS, mobileCaseHref: caseHrefS } = M_SC;

// Resolve a service by id, with legacy-ID fallback (old links in read-only files:
// spot/maint/full/reform — declared as `aliases` on the new SERVICES entries).
const currentServiceM = () => {
  const serviceId = new URLSearchParams(window.location.search).get('service');
  return SV_S.find((s) => s.id === serviceId)
    || SV_S.find((s) => (s.aliases || []).includes(serviceId))
    || SV_S[0];
};

// Before/Afterペアは「before と after が両方設定された事例」に自動表示する。
// （旧: repo写真時代のID許可リスト。CMS移行後はクライアントが同一箇所ペアを登録する運用のため、
//  リスト方式だと新規事例が施工後のみ表示になる不具合の原因になっていた）
const isPairedCase = (c) => Boolean(c.before && c.after && c.before !== c.after);

// Hero title emphasis: color key trade words orange (design.md hero-block: 強調語をオレンジ着色).
// Shared components stay untouched — we pass JSX into HeroS title.
const HL_WORDS_M = ['雨漏り', '屋根', '外壁', '葺き替え', 'カバー工法', '塗装', '補修', 'メンテナンス', '改修'];
function MHLTitle({ text }) {
  if (typeof text !== 'string') return text;
  const re = new RegExp(`(${HL_WORDS_M.join('|')})`, 'g');
  return <>{text.split(re).map((part, i) =>
    HL_WORDS_M.includes(part)
      ? <span key={i} style={{ color: TS.oMain }}>{part}</span>
      : <React.Fragment key={i}>{part}</React.Fragment>
  )}</>;
}

// ---- shared B-option bits (local compositions of shared tokens; no component variants) ----

// 施工前/施工後 tag — label-before(ink) / label-after(orange), radius 3, photo-hugging.
function MCaseTag({ after, children }) {
  return (
    <div style={{ position: 'absolute', top: 6, left: 6, zIndex: 1, background: after ? TS.oMain : TS.ink, color: '#fff', fontSize: 12, fontWeight: 800, padding: '3px 7px', borderRadius: 3, lineHeight: 1 }}>
      {children || (after ? '施工後' : '施工前')}
    </div>
  );
}

// Before/After pair with orange circle arrow (design.md pattern 9).
function MBAPair({ before, after, ratio = '4/3', beforeAlt = '', afterAlt = '' }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
      <div style={{ position: 'relative' }}>
        <MCaseTag>施工前</MCaseTag>
        <ImgS src={before} ratio={ratio} radius={5} alt={beforeAlt} style={{ filter: 'saturate(0.7) brightness(0.96)' }} />
        <span style={{ position: 'absolute', top: '50%', right: -11, transform: 'translateY(-50%)', zIndex: 2, width: 22, height: 22, borderRadius: '50%', background: TS.oMain, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 6px rgba(0,0,0,0.25)' }}>
          <IcS.arrow width="13" height="13" color="#fff" />
        </span>
      </div>
      <div style={{ position: 'relative' }}>
        <MCaseTag after>施工後</MCaseTag>
        <ImgS src={after} ratio={ratio} radius={5} alt={afterAlt} />
      </div>
    </div>
  );
}

// Bottom phone CTA (shared card) with consistent section padding.
function MPhoneCTASection({ note }) {
  return (
    <section style={{ background: '#fff', padding: '10px 16px 16px' }}>
      {note && (
        <div style={{ textAlign: 'center', fontFamily: '"Noto Sans JP", sans-serif', fontSize: 14.5, fontWeight: 700, color: TS.ink, margin: '0 0 8px' }}>
          {note}
        </div>
      )}
      <PhoneCardS />
    </section>
  );
}

// ===== Service Index =====
function MPageServicesIndex() {
  return (
    <PageS active="services">
      <HeroS
        title={<><span style={{ color: TS.oMain }}>屋根</span>・<span style={{ color: TS.oMain }}>外壁</span>・<span style={{ color: TS.oMain }}>雨漏り</span>の対応サービス</>}
        lead="住まいの気になることを、ひとつの窓口で承ります。屋根・外壁の修理から、内装・水回りまでまとめてご相談いただけます。"
        breadcrumb={<>ホーム ／ <span style={{ color: TS.ink }}>サービス一覧</span></>}
        divider={false}
      />

      {/* 対応サービス：2列グリッドのタイル（緑線アイコン＋工種名＋一行説明＋実写サムネ＋オレンジ矢印） */}
      <section style={{ background: '#fff', padding: '14px 16px 4px' }}>
        {/* ページ見出し（h1）と同名の帯は重複になるため置かない（Codex/Opusレビュー指摘） */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9 }}>
          {SV_S.map((s, i) => {
            const iconKey = S_SC.serviceIconKey(s);
            const SvIc = IcS[iconKey] || IcS.home;
            const fullWidth = SV_S.length % 2 === 1 && i === SV_S.length - 1;
            return (
              <a key={s.id} href={serviceHrefS(s.id)} style={{
                position: 'relative', display: 'flex', flexDirection: 'column', gap: 6,
                border: `1px solid ${TS.line}`, borderRadius: 8, background: '#fff',
                padding: '10px 10px 10px', textDecoration: 'none', minHeight: 44,
                gridColumn: fullWidth ? '1 / -1' : 'auto',
              }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 6, paddingRight: 15 }}>
                  <span data-service-icon={iconKey}><SvIc width="20" height="20" color={TS.green} style={{ flexShrink: 0 }} /></span>
                  <span style={{ color: TS.ink, fontWeight: 800, fontSize: 'clamp(13px, 3.8vw, 15px)', letterSpacing: -0.2, lineHeight: 1.35, minWidth: 0, wordBreak: 'auto-phrase', overflowWrap: 'break-word', fontFeatureSettings: "'palt'" }}>{s.name}</span>
                </span>
                {/* slot: TEXT-SERVICE-INDEX-BLURB */}
                {hasTextS(s.blurb) && <span data-empty-contract="service-card-blurb" data-text-contract="narrow-service-blurb" data-service-id={s.id} style={{ display: 'block', color: TS.ink70, fontWeight: 400, fontSize: 11.5, lineHeight: 1.6, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}><BTS>{s.blurb}</BTS></span>}
                {/* slot: LOWER-SERVICE-IMAGE-{s.id} */}
                {hasImageRefS(s.photo) && <span data-empty-contract="service-card-photo" data-service-id={s.id} style={{ display: 'block', marginTop: 'auto' }}>
                  <ImgS src={s.photo} ratio={fullWidth ? '16/6' : '16/9'} radius={5} />
                </span>}
                <IcS.arrow width="15" height="15" color={TS.oDeep} style={{ position: 'absolute', top: 12, right: 9 }} />
              </a>
            );
          })}
        </div>
      </section>

      {/* 施工事例でわかる（case-proof-card 型・中立の帯） */}
      <section style={{ background: '#fff', padding: '8px 16px 4px' }}>
        <div style={{ border: `1px solid ${TS.line}`, borderRadius: 9, overflow: 'hidden', background: '#fff' }}>
          <div style={{ background: TS.greenSoft, color: TS.greenInk, textAlign: 'center', fontSize: 15, fontWeight: 800, padding: '9px 12px', letterSpacing: 0.3, borderBottom: `1px solid ${TS.line}` }}>
            施工事例でわかる！実際の施工をご紹介
          </div>
          <div style={{ padding: 10 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {/* slot: CASE-01-BEFORE / CASE-01-AFTER, CASE-02-BEFORE / CASE-02-AFTER（CMSの事例が1件でも落ちないよう先頭2件を描画） */}
              {CASES_S.slice(0, 2).map((c, i) => (
                <MBAPair key={c.id || i} before={c.before} after={c.after} ratio="1/1" beforeAlt={`${c.work}（${c.cat}）の施工前写真`} afterAlt={`${c.work}（${c.cat}）の施工後写真`} />
              ))}
            </div>
            <a href={hrefS('cases')} style={{
              marginTop: 10, height: 44, border: `1.5px solid ${TS.oLine}`, borderRadius: 8,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              color: TS.oDeep, fontWeight: 800, fontSize: 15, textDecoration: 'none', position: 'relative',
            }}>
              <IcS.camera width="18" height="18" color={TS.oDeep} /> 施工事例を見る
              <IcS.arrow width="16" height="16" color={TS.oDeep} style={{ position: 'absolute', right: 14 }} />
            </a>
          </div>
        </div>
      </section>

      <MPhoneCTASection />
    </PageS>
  );
}

// ===== Service Detail =====
// CMSで明示的に空にされたら訴求行ごと出さない（未設定なら既定値）
const inspectionNoteM = () => {
  const raw = rawCopyS('service.inspection.note');
  return String(raw === undefined ? '建物の状態を把握する、建物の健康診断。' : raw).trim();
};

function MPageServiceDetail() {
  const s = currentServiceM();
  const related = CASES_S.filter(isPairedCase).slice(0, 2);
  const symptoms = Array.isArray(s.symptoms) ? s.symptoms.filter((x) => x && (hasTextS(x.t) || hasTextS(x.d))) : [];
  const durations = Array.isArray(s.durations) ? s.durations.filter((x) => x && (hasTextS(x.kind) || hasTextS(x.day))) : [];
  return (
    <PageS active="services">
      <HeroS
        title={<MHLTitle text={s.name} />}
        lead={s.blurb}
        breadcrumb={<>
          <a href={hrefS('top')} style={{ color: TS.ink70, textDecoration: 'none' }}>ホーム</a> ／{' '}
          <a href={hrefS('services')} style={{ color: TS.ink70, textDecoration: 'none' }}>サービス一覧</a> ／{' '}
          <span style={{ color: TS.ink }}>{s.name}</span>
        </>}
      />
      {/* 点検・診断系のサービスだけ、冒頭に一行の訴求（CMS: service.inspection.note）を細い緑罫つきで添える */}
      {/点検|診断/.test(String(s.name || '')) && inspectionNoteM(s) && (
        <section style={{ background: '#fff', padding: '12px 16px 0' }}>
          <p style={{ display: 'flex', alignItems: 'center', gap: 8, margin: 0, fontFamily: '"Noto Sans JP", sans-serif', fontSize: 12.5, fontWeight: 700, color: TS.green, lineHeight: 1.6 }}>
            <span aria-hidden="true" style={{ width: 18, height: 1.5, background: TS.green, flexShrink: 0 }} />
            {inspectionNoteM(s)}
          </p>
        </section>
      )}
      {hasImageRefS(s.photo) && <section data-empty-contract="service-hero-photo" data-service-id={s.id} style={{ background: '#fff', padding: '12px 16px 4px' }}>
        {/* slot: LOWER-SERVICE-IMAGE-MAIN */}
        <ImgS src={s.photo} ratio="16/9" radius={8} priority />
      </section>}

      {/* こんな症状ありませんか（症状チップ群） */}
      {symptoms.length > 0 && <section data-empty-contract="service-symptoms" data-service-id={s.id} style={{ background: '#fff', padding: '12px 16px 4px' }}>
        <SHS band title="こんな症状ありませんか">
          <div style={{ display: 'grid', gap: 9 }}>
            {symptoms.map((x, i) => (
              <div key={`${i}-${String(x.t)}`} data-empty-row style={{
                display: 'grid', gridTemplateColumns: '30px 1fr', gap: 10, alignItems: 'start',
                border: `1px solid ${TS.line}`, borderRadius: 8, background: '#fff', padding: '11px 12px',
              }}>
                <IcS.alert width="22" height="22" color={TS.green} style={{ marginTop: 1 }} />
                <div>
                  {hasTextS(x.t) && <div style={{ color: TS.ink, fontWeight: 800, fontSize: 13.5, lineHeight: 1.5 }}>{x.t}</div>}
                  {hasTextS(x.d) && <div style={{ color: TS.ink70, fontSize: 12, lineHeight: 1.8, marginTop: hasTextS(x.t) ? 3 : 0 }}><BTS>{x.d}</BTS></div>}
                </div>
              </div>
            ))}
          </div>
        </SHS>
      </section>}

      {durations.length > 0 && (
        <section data-empty-contract="service-durations" data-service-id={s.id} style={{ background: '#fff', padding: '4px 16px 4px' }}>
          <SHS band title="目安">
            <div style={{ display: 'grid', gap: 9 }}>
              {durations.map((x, i) => (
                <div key={`${i}-${String(x.kind)}`} data-empty-row style={{
                  display: 'grid', gridTemplateColumns: '30px 1fr', gap: 10, alignItems: 'start',
                  border: `1px solid ${TS.line}`, borderRadius: 8, background: '#fff', padding: '11px 12px',
                }}>
                  <IcS.clock width="22" height="22" color={TS.green} style={{ marginTop: 1 }} />
                  <div>
                    {hasTextS(x.kind) && <div style={{ color: TS.ink, fontWeight: 800, fontSize: 13.5, lineHeight: 1.5 }}>{x.kind}</div>}
                    {hasTextS(x.day) && <div style={{ color: TS.ink70, fontSize: 12, lineHeight: 1.8, marginTop: hasTextS(x.kind) ? 3 : 0 }}><BTS>{x.day}</BTS></div>}
                  </div>
                </div>
              ))}
            </div>
          </SHS>
        </section>
      )}

      {/* 施工の流れ */}
      <section style={{ background: '#fff', padding: '4px 16px 4px' }}>
        <SHS title="ご相談から完工までの流れ" lead="まずはお客さまのご要望や現状を、やさしい言葉で確認するところから始めます。" />
        <div style={{ display: 'grid', gap: 0 }}>
          {FLOW_S.map((x, i) => (
            <div key={x.n} style={{ display: 'grid', gridTemplateColumns: '36px 1fr', gap: 12, padding: '13px 0', borderBottom: i < FLOW_S.length - 1 ? `1px solid ${TS.line}` : 'none' }}>
              <span style={{ width: 30, height: 30, borderRadius: '50%', background: TS.green, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 14, lineHeight: 1 }}>{x.n || i + 1}</span>
              <div>
                <div style={{ color: TS.ink, fontWeight: 800, fontSize: 14.5, lineHeight: 1.5 }}>{x.title}</div>
                <div data-flow-body={x.n} style={{ color: TS.ink70, fontSize: 12.5, lineHeight: 1.85, marginTop: 3, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}><BTS noBreakPhrases={FLOW_NO_BREAK_S}>{x.body}</BTS></div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* 関連 Before/After（case-proof-card 型） */}
      {related.length > 0 && <section data-empty-contract="service-related-cases" data-service-id={s.id} style={{ background: '#fff', padding: '8px 16px 4px' }}>
        <div style={{ border: `1px solid ${TS.line}`, borderRadius: 9, overflow: 'hidden', background: '#fff' }}>
          <div style={{ background: TS.greenSoft, color: TS.greenInk, textAlign: 'center', fontSize: 15, fontWeight: 800, padding: '9px 12px', letterSpacing: 0.3, borderBottom: `1px solid ${TS.line}` }}>
            施工事例でわかる
          </div>
          <div style={{ padding: 10 }}>
            <div style={{ display: 'grid', gap: 12 }}>
              {related.map((c) => (
                <a key={c.id} href={caseHrefS(c.id)} style={{ textDecoration: 'none', display: 'block' }}>
                  {/* slot: CASE-{c.id}-BEFORE / CASE-{c.id}-AFTER */}
                  <MBAPair before={c.before} after={c.after} ratio="4/3" beforeAlt={`${c.work}（${c.cat}）の施工前写真`} afterAlt={`${c.work}（${c.cat}）の施工後写真`} />
                  <div style={{ color: TS.ink, fontWeight: 800, fontSize: 13, marginTop: 7, lineHeight: 1.5 }}>{c.work}</div>
                </a>
              ))}
            </div>
            <a href={hrefS('cases')} style={{
              marginTop: 10, height: 44, border: `1.5px solid ${TS.oLine}`, borderRadius: 8,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              color: TS.oDeep, fontWeight: 800, fontSize: 15, textDecoration: 'none', position: 'relative',
            }}>
              <IcS.camera width="18" height="18" color={TS.oDeep} /> 施工事例を見る
              <IcS.arrow width="16" height="16" color={TS.oDeep} style={{ position: 'absolute', right: 14 }} />
            </a>
          </div>
        </div>
      </section>}

      <MPhoneCTASection />
    </PageS>
  );
}

// ===== Cases Index =====
const M_CATS = ['すべて'].concat(CASES_S.map((c) => c.cat).filter((cat, i, arr) => cat && arr.indexOf(cat) === i));
const currentCaseCatM = () => new URLSearchParams(window.location.search).get('cat') || 'すべて';
const caseCatHrefM = (cat) => cat === 'すべて' ? hrefS('cases') : `${hrefS('cases')}&cat=${encodeURIComponent(cat)}`;
const currentCaseM = () => {
  const caseId = new URLSearchParams(window.location.search).get('case');
  return CASES_S.find((c) => c.id === caseId) || CASES_S[0];
};

// 値が「工期 約20日」「築35〜40年」のようにラベル相当の語で始まるときは、ラベルを付けずに値だけ出す。
// （CMS値は変えない。ラベル＋値が「工期：工期 約20日」と重複するのを防ぐ）
const labelledMetaText = (label, heads, value) => {
  const text = String(value || '').trim();
  if (!text) return '';
  const carriesLabel = heads.some((head) => text.startsWith(head));
  return carriesLabel ? text : `${label}：${text}`;
};

function MCaseMetaChips({ c, showDetailMeta = false }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, border: `1px solid ${TS.line}`, borderRadius: 999, padding: '3px 9px', fontSize: 11, fontWeight: 800, color: TS.greenInk }}>
        <IcS.home width="11" height="11" color={TS.green} /> {c.cat}
      </span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, border: `1px solid ${TS.line}`, borderRadius: 999, padding: '3px 9px', fontSize: 11, fontWeight: 800, color: TS.ink70 }}>
        <IcS.pin width="11" height="11" color={TS.green} /> {c.area || '広島市・周辺エリア'}
      </span>
      {showDetailMeta && c.year && (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, border: `1px solid ${TS.line}`, borderRadius: 999, padding: '3px 9px', fontSize: 11, fontWeight: 800, color: TS.ink70 }}>
          <IcS.clock width="11" height="11" color={TS.green} /> {labelledMetaText('築年数', ['築年数', '築'], c.year)}
        </span>
      )}
      {showDetailMeta && c.term && (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, border: `1px solid ${TS.line}`, borderRadius: 999, padding: '3px 9px', fontSize: 11, fontWeight: 800, color: TS.ink70 }}>
          <IcS.clock width="11" height="11" color={TS.green} /> {labelledMetaText('工期', ['工期'], c.term)}
        </span>
      )}
    </div>
  );
}

function MPageCasesIndex() {
  const activeCat = currentCaseCatM();
  const visibleCases = activeCat === 'すべて' ? CASES_S : CASES_S.filter((c) => c.cat === activeCat);
  return (
    <PageS active="cases">
      <HeroS
        title="施工事例でわかる"
        lead={`実際の施工をご紹介します。${CO_S.area}で対応させていただいた事例の一部です。`}
        breadcrumb={<>ホーム ／ <span style={{ color: TS.ink }}>施工事例</span></>}
      />

      {/* 工種フィルタ：お役立ちと同じ「白＋細罫＋緑アイコン」様式。選択中だけオレンジ塗り */}
      <section style={{ background: '#fff', padding: '12px 16px 4px' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, paddingBottom: 4 }}>
          {M_CATS.map((cat) => {
            const active = activeCat === cat;
            return (
              <a key={cat} href={caseCatHrefM(cat)} style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                minHeight: 36, padding: '6px 12px', fontSize: 12.5, fontWeight: 800,
                color: active ? '#fff' : TS.ink,
                background: active ? TS.green : '#fff',
                border: active ? `1.5px solid ${TS.green}` : `1px solid ${TS.line}`,
                borderRadius: 8, whiteSpace: 'nowrap', textDecoration: 'none',
              }}>
                <IcS.home width="15" height="15" color={active ? '#fff' : TS.green} style={{ flexShrink: 0 }} />
                {cat}
              </a>
            );
          })}
        </div>
      </section>

      {/* Before/Afterペアカード縦積み（確認済みペアのみ。それ以外はAfter単体） */}
      <section style={{ background: '#fff', padding: '10px 16px 4px' }}>
        {visibleCases.length ? (
          <div style={{ display: 'grid', gap: 12 }}>
            {visibleCases.map((c) => (
              <div key={c.id} style={{ border: `1px solid ${TS.line}`, borderRadius: 9, overflow: 'hidden', background: '#fff' }}>
                {/* 見出し帯は情報表示なので中立色にする（オレンジは押す場所だけに残す） */}
                <div style={{ background: TS.greenSoft, color: TS.greenInk, textAlign: 'center', fontSize: 14, fontWeight: 800, padding: '7px 12px', lineHeight: 1.45, borderBottom: `1px solid ${TS.line}` }}>
                  {c.work}
                </div>
                <div style={{ padding: 10 }}>
                  {isPairedCase(c) ? (
                    /* slot: CASE-{c.id}-BEFORE / CASE-{c.id}-AFTER */
                    <MBAPair before={c.before} after={c.after} ratio="4/3" beforeAlt={`${c.work}（${c.cat}）の施工前写真`} afterAlt={`${c.work}（${c.cat}）の施工後写真`} />
                  ) : (
                    <div style={{ position: 'relative' }}>
                      {/* slot: CASE-{c.id}-AFTER */}
                      <MCaseTag after>施工後</MCaseTag>
                      <ImgS src={c.after} ratio="16/9" radius={5} alt={`${c.work}（${c.cat}）の施工後写真`} />
                    </div>
                  )}
                  <div style={{ margin: '9px 0 8px' }}>
                    <MCaseMetaChips c={c} />
                  </div>
                  <div style={{ fontSize: 12.5, color: TS.ink70, lineHeight: 1.85 }}><BTS>{c.summary}</BTS></div>
                  {/* モック03：右寄せのコンパクトなボタン */}
                  <a href={caseHrefS(c.id)} style={{
                    marginTop: 9, marginLeft: 'auto', height: 44, minWidth: 132, width: 'fit-content',
                    border: `1.5px solid ${TS.oLine}`, borderRadius: 8, padding: '0 14px',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    color: TS.oDeep, fontWeight: 800, fontSize: 14, textDecoration: 'none',
                  }}>
                    詳しく見る
                    <IcS.arrow width="15" height="15" color={TS.oDeep} />
                  </a>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ border: `1.5px solid ${TS.oLine}`, borderRadius: 9, background: '#fff', padding: '18px 14px', textAlign: 'center' }}>
            <p style={{ margin: '0 0 12px', color: TS.ink70, fontSize: 13, lineHeight: 1.8 }}>このカテゴリの事例は現在準備中です。「すべて」から他の事例をご覧ください。</p>
            <a href={hrefS('cases')} style={{ color: TS.oDeep, fontWeight: 800, fontSize: 13, textDecoration: 'none', borderBottom: `1.5px solid ${TS.oDeep}`, paddingBottom: 3 }}>すべての事例を見る</a>
          </div>
        )}
      </section>

      <MPhoneCTASection note="似た症状はお電話でご相談ください" />
    </PageS>
  );
}

// ===== Case Detail =====
function MPageCaseDetail() {
  const c = currentCaseM();
  const paired = isPairedCase(c);
  const fallbackFlow = [
    { ph: S_SC.ASSETS.heroWide1, t: '現地確認', d: '屋根に上がって状況を確認し、雨水の経路となりうる場所を見ていきました。' },
    { ph: S_SC.ASSETS.case2, t: '施工', d: '合意した範囲を施工。進捗は撮影しながらお伝えしました。' },
    { ph: S_SC.ASSETS.case1, t: '完工確認', d: '完工後にご一緒に確認いただきました。' },
  ];
  const rawFlow = Object.prototype.hasOwnProperty.call(c, 'flow') ? c.flow : fallbackFlow;
  const flow = Array.isArray(rawFlow) ? rawFlow.filter((x) => x && (hasTextS(x.t) || hasTextS(x.d) || hasImageRefS(x.ph))) : [];
  return (
    <PageS active="cases">
      <HeroS
        title={c.work /* モック04：事例題はink無着色（工種語着色だと全文オレンジになる） */}
        lead={c.summary}
        breadcrumb={<>
          <a href={hrefS('top')} style={{ color: TS.ink70, textDecoration: 'none' }}>ホーム</a> ／{' '}
          <a href={hrefS('cases')} style={{ color: TS.ink70, textDecoration: 'none' }}>施工事例</a> ／{' '}
          <span style={{ color: TS.ink }}>{c.work}</span>
        </>}
      />

      {/* 確認済みメタ */}
      <section style={{ background: '#fff', padding: '12px 16px 0' }}>
        <MCaseMetaChips c={c} showDetailMeta />
      </section>

      {/* 大きい Before/After */}
      <section style={{ background: '#fff', padding: '12px 16px 4px' }}>
        {paired ? (
          /* モック04：大きいBefore/Afterは左右並び＋オレンジ円矢印 */
          /* slot: CASE-{c.id}-BEFORE / CASE-{c.id}-AFTER */
          <MBAPair before={c.before} after={c.after} ratio="1/1" beforeAlt={`${c.work}（${c.cat}）の施工前写真`} afterAlt={`${c.work}（${c.cat}）の施工後写真`} />
        ) : (
          <div style={{ position: 'relative' }}>
            {/* slot: CASE-{c.id}-AFTER */}
            <MCaseTag after>施工後</MCaseTag>
            <ImgS src={c.after} ratio="16/9" radius={8} priority alt={`${c.work}（${c.cat}）の施工後写真`} />
          </div>
        )}
      </section>

      {/* 施工の記録（作業過程写真：flowを持つ事例のみ） */}
      {flow.length > 0 && (
        <section data-empty-contract="case-flow" data-case-id={c.id} style={{ background: '#fff', padding: '8px 16px 4px' }}>
          <SHS band title="施工の記録">
            <div style={{ display: 'grid', gap: 0 }}>
              {flow.map((x, i) => (
                <div key={i} data-empty-row style={{ padding: '11px 0', borderBottom: i < flow.length - 1 ? `1px solid ${TS.line}` : 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                    <span style={{ width: 26, height: 26, borderRadius: '50%', background: TS.green, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13, lineHeight: 1, flexShrink: 0 }}>{i + 1}</span>
                    {hasTextS(x.t) && <span style={{ color: TS.ink, fontWeight: 800, fontSize: 14 }}>{x.t}</span>}
                  </div>
                  {/* slot: CASE-{c.id}-FLOW-{i+1} */}
                  {hasImageRefS(x.ph) && <ImgS src={x.ph} ratio="16/9" radius={6} alt={`${c.work}の工程${i + 1}（${x.t}）写真`} />}
                  {hasTextS(x.d) && <div style={{ fontSize: 12, color: TS.ink70, lineHeight: 1.85, marginTop: hasImageRefS(x.ph) ? 8 : 0 }}><BTS>{x.d}</BTS></div>}
                </div>
              ))}
            </div>
          </SHS>
        </section>
      )}

      <MPhoneCTASection note="似た症状はお電話でご相談ください" />
    </PageS>
  );
}

window.MPageServicesIndex = MPageServicesIndex;
window.MPageServiceDetail = MPageServiceDetail;
window.MPageCasesIndex = MPageCasesIndex;
window.MPageCaseDetail = MPageCaseDetail;
