// Service index + detail pages.

const SP = window.Site;
const { T: TP, COMPANY: COP, SERVICES: SVP, FLOW_STEPS: FLOWP, FLOW_NO_BREAK: FLOW_NO_BREAK_P, CoverImg: ImgP, Icon: IcP, Btn: BtnP, SectionHeading: SHP, CASES: CASESP, Page: PageP, PageHero: HeroP, PlaceholderTag: PTP, siteHref: hrefP, siteServiceHref: serviceHrefP, siteCaseHref: caseHrefP, rawCopyValue: rawCopyP, caseNumberLabel: caseNumberP, hasText: hasTextP, hasImageRef: hasImageRefP } = SP;
const currentService = () => {
  const serviceId = new URLSearchParams(window.location.search).get('service');
  return SVP.find((s) => s.id === serviceId)
    || SVP.find((s) => (s.aliases || []).includes(serviceId))
    || SVP[0];
};
const serviceNumber = (service) => String(SVP.findIndex((s) => s.id === service.id) + 1).padStart(2, '0');

// ---------------- Service Index ----------------
function PageServicesIndex() {
  return (
    <PageP active="services">
      <HeroP num="01" en="SERVICE" title="サービス一覧" lead="屋根・外壁の修理から、内装・水回りまで、住まいのことをまとめてご相談いただけます。気になることがあれば、まずはお電話またはメールでお気軽にお問い合わせください。" />
      <section style={{ background: '#fff', padding: '60px 56px 88px' }}>
        <div data-pc-readable="services-index" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 0, maxWidth: 1280, margin: '0 auto' }}>
          {SVP.map((s, i) => {
            const flip = i % 2 === 1;
            const iconKey = SP.serviceIconKey(s);
            const ServiceIcon = IcP[iconKey] || IcP.home;
            const hasPhoto = hasImageRefP(s.photo);
            const hasSymptoms = Array.isArray(s.symptoms) && s.symptoms.some((x) => x && (hasTextP(x.t) || hasTextP(x.d)));
            const hasDurations = Array.isArray(s.durations) && s.durations.some((x) => x && (hasTextP(x.kind) || hasTextP(x.day)));
            const features = [
              hasSymptoms && '対象となる症状',
              '工程の進め方',
              hasDurations && '工期の目安',
              CASESP.length > 0 && '関連する事例',
            ].filter(Boolean);
            return (
              <div key={s.id} style={{
                display: 'grid', gridTemplateColumns: hasPhoto ? (flip ? '1fr 1.1fr' : '1.1fr 1fr') : '1fr',
                gap: hasPhoto ? 56 : 0, alignItems: 'center',
                padding: '36px 0', borderBottom: `1px solid ${TP.line}`, borderTop: i === 0 ? `1px solid ${TP.line}` : 'none',
              }}>
                {hasPhoto && <div data-empty-contract="service-card-photo" data-service-id={s.id} style={{ order: flip ? 2 : 1 }}>
                  <ImgP src={s.photo} ratio="4/3" radius={6} />
                </div>}
                <div style={{ order: flip ? 1 : 2 }}>
                  <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 11, color: TP.green, letterSpacing: 3, marginBottom: 10, fontWeight: 700 }}>
                    {'0' + (i + 1)} / SERVICE
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontFamily: '"Noto Sans JP", sans-serif', fontSize: 30, fontWeight: 700, color: TP.ink, lineHeight: 1.4, marginBottom: 14 }}><span data-service-icon={iconKey}><ServiceIcon width="30" height="30" color={TP.green} /></span>{s.name}</div>
                  {hasTextP(s.blurb) && <div data-empty-contract="service-card-blurb" data-service-id={s.id} style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 15, color: TP.ink70, lineHeight: 2.05, marginBottom: 18, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}><SP.BudouXText>{s.blurb}</SP.BudouXText></div>}
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 22, maxWidth: 480 }}>
                    {features.map((t) => (
                      <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: TP.ink80 }}>
                        <span style={{ width: 4, height: 4, background: TP.green, borderRadius: 0 }} /> {t}
                      </div>
                    ))}
                  </div>
                  <a href={serviceHrefP(s.id)} style={{ fontSize: 13.5, color: TP.ink, fontWeight: 700, borderBottom: `1.5px solid ${TP.ink}`, paddingBottom: 3, display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none' }}>
                    詳しく見る <IcP.arrow width="14" height="14" />
                  </a>
                </div>
              </div>
            );
          })}
        </div>
      </section>

    </PageP>
  );
}

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

// ---------------- Service Detail ----------------
function PageServiceDetail() {
  const s = currentService();
  const n = serviceNumber(s);
  const symptoms = Array.isArray(s.symptoms) ? s.symptoms.filter((x) => x && (hasTextP(x.t) || hasTextP(x.d))) : [];
  const durations = Array.isArray(s.durations) ? s.durations.filter((x) => x && (hasTextP(x.kind) || hasTextP(x.day))) : [];
  const related = CASESP.slice(0, 3);
  let nextSectionNumber = 1;
  const sectionNumbers = {};
  if (symptoms.length) sectionNumbers.symptoms = String(nextSectionNumber++).padStart(2, '0');
  sectionNumbers.flow = String(nextSectionNumber++).padStart(2, '0');
  if (durations.length) sectionNumbers.durations = String(nextSectionNumber++).padStart(2, '0');
  if (related.length) sectionNumbers.related = String(nextSectionNumber++).padStart(2, '0');
  return (
    <PageP active="services">
      <section style={{ background: TP.paper, padding: '40px 56px 0' }}>
        <SP.Breadcrumb items={['ホーム', 'サービス一覧', s.name]} />
      </section>
      <section style={{ background: TP.paper, padding: '28px 56px 60px', borderBottom: `1px solid ${TP.line}` }}>
        <div style={{ display: 'grid', gridTemplateColumns: hasImageRefP(s.photo) ? '1.05fr 1fr' : '1fr', gap: hasImageRefP(s.photo) ? 48 : 0, alignItems: 'end' }}>
          <div>
            <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 11, color: TP.green, letterSpacing: 4, marginBottom: 14, fontWeight: 700 }}>{n} / SERVICE — {s.name}</div>
            <h1 style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 52, fontWeight: 900, color: TP.ink, margin: 0, lineHeight: 1.3, letterSpacing: '-0.02em', fontFeatureSettings: "'palt'" }}>
              {s.name}
            </h1>
            {/* 点検・診断系のサービスだけ、見出し直下に一行の訴求（CMS: service.inspection.note） */}
            {/点検|診断/.test(String(s.name || '')) && inspectionNoteP() && (
              <p style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '16px 0 0', fontFamily: '"Noto Sans JP", sans-serif', fontSize: 14, fontWeight: 700, color: TP.green, lineHeight: 1.7 }}>
                <span aria-hidden="true" style={{ width: 24, height: 1.5, background: TP.green, flexShrink: 0 }} />
                {inspectionNoteP()}
              </p>
            )}
            <p data-text-contract="subpage-hero-lead" style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 16, color: TP.ink70, lineHeight: 2.1, marginTop: 18, maxWidth: hasImageRefP(s.photo) ? 540 : 'none', wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}>
              <SP.BudouXText>{s.blurb}</SP.BudouXText>
            </p>
          </div>
          {hasImageRefP(s.photo) && (
            <ImgP src={s.photo} ratio="4/3" radius={6} priority dataEmptyContract="service-hero-photo" dataServiceId={s.id} />
          )}
        </div>
      </section>

      {/* 対象となる症状 */}
      {symptoms.length > 0 && (
      <section data-empty-contract="service-symptoms" data-service-id={s.id} style={{ background: '#fff', padding: '72px 56px', borderBottom: `1px solid ${TP.line}` }}>
        <SHP num={sectionNumbers.symptoms} en="SYMPTOMS" title="対象となる症状" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
          {symptoms.map((x, i) => (
            <div key={`${i}-${String(x.t)}`} data-empty-row style={{ border: `1px solid ${TP.line}`, padding: 22, borderRadius: 6 }}>
              <div style={{ color: TP.green, marginBottom: 12 }}><IcP.alert width="20" height="20" /></div>
              {hasTextP(x.t) && <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 18, fontWeight: 700, color: TP.ink, marginBottom: hasTextP(x.d) ? 10 : 0, lineHeight: 1.5 }}>{x.t}</div>}
              {hasTextP(x.d) && <div style={{ fontSize: 13, color: TP.ink70, lineHeight: 1.95 }}>{x.d}</div>}
            </div>
          ))}
        </div>
      </section>
      )}

      {/* 工程 */}
      <section style={{ background: TP.paper, padding: '72px 56px', borderBottom: `1px solid ${TP.line}` }}>
        <SHP num={sectionNumbers.flow} en="FLOW" title="ご相談から完工までの流れ" lead="まずはお客さまのご要望や現状を丁寧にお伺いします。" />
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.max(FLOWP.length, 1)}, 1fr)`, gap: 0 }}>
          {FLOWP.map((x, i) => (
            <div key={x.n} style={{ paddingRight: 22, borderRight: i < FLOWP.length - 1 ? `1px solid ${TP.line}` : 'none', paddingLeft: i > 0 ? 22 : 0 }}>
              <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 36, color: TP.orange, fontWeight: 700, lineHeight: 1 }}>{x.n}</div>
              <div style={{ height: 1, background: TP.line, margin: '14px 0 16px' }} />
              <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 19, fontWeight: 700, color: TP.ink, marginBottom: 10 }}>{x.title}</div>
              <div data-flow-body={x.n} style={{ fontSize: 13, color: TP.ink70, lineHeight: 1.95, wordBreak: 'auto-phrase', overflowWrap: 'break-word' }}><SP.BudouXText noBreakPhrases={FLOW_NO_BREAK_P}>{x.body}</SP.BudouXText></div>
            </div>
          ))}
        </div>
      </section>

      {/* 工期目安 */}
      {durations.length > 0 && (
      <section data-empty-contract="service-durations" data-service-id={s.id} style={{ background: '#fff', padding: '72px 56px', borderBottom: `1px solid ${TP.line}` }}>
        <SHP num={sectionNumbers.durations} en="DURATION" title={<>工期の目安 <PTP /></>} lead="工期の目安は、現場の状況や工法によって大きく変わります。下記はあくまで一般的な範囲としての目安で、正確な期間は現地調査後にご案内します。" align="left" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, borderBottom: `1px solid ${TP.line}` }}>
          {durations.map((x, i) => (
            <div key={`${i}-${String(x.kind)}`} data-empty-row style={{ padding: '24px 28px', borderRight: i < durations.length - 1 ? `1px solid ${TP.line}` : 'none' }}>
              {hasTextP(x.kind) && <div style={{ fontSize: 12, color: TP.orangeDeep, fontWeight: 700, letterSpacing: 1.5, marginBottom: 6 }}>工事の種類</div>}
              {hasTextP(x.kind) && <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 22, fontWeight: 700, color: TP.ink, marginBottom: hasTextP(x.day) ? 10 : 0 }}>{x.kind}</div>}
              {hasTextP(x.day) && <div style={{ fontSize: 14, color: TP.ink70 }}>{x.day}</div>}
            </div>
          ))}
        </div>
      </section>
      )}

      {/* 関連事例 */}
      {related.length > 0 && (
      <section data-empty-contract="service-related-cases" data-service-id={s.id} style={{ background: TP.paper, padding: '72px 56px', borderBottom: `1px solid ${TP.line}` }}>
        <SHP num={sectionNumbers.related} en="RELATED WORKS" title="関連する施工事例" anchorRight={
          <a href={hrefP('cases')} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 12, color: TP.ink, fontSize: 13.5, fontWeight: 700, borderBottom: `1.5px solid ${TP.ink}`, paddingBottom: 3, textDecoration: 'none' }}>
            施工事例をすべて見る <IcP.arrow width="14" height="14" />
          </a>
        } />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {related.map((c) => (
            <a key={c.id} href={caseHrefP(c.id)} style={{ display: 'block', background: '#fff', borderRadius: 6, overflow: 'hidden', textDecoration: 'none' }}>
              <ImgP src={c.photo || c.after} ratio="4/3" />
              <div style={{ padding: 18 }}>
                {caseNumberP(c.id) && (
                  <div style={{ fontSize: 11, color: TP.orangeDeep, fontWeight: 700, letterSpacing: 1.5, marginBottom: 8 }}>{caseNumberP(c.id)}</div>
                )}
                <div style={{ fontFamily: '"Noto Sans JP", sans-serif', fontSize: 16, fontWeight: 700, color: TP.ink, lineHeight: 1.5, marginBottom: 6 }}>{c.work}</div>
                <div style={{ fontSize: 12, color: TP.ink70 }}>{c.area} ／ {c.term}</div>
              </div>
            </a>
          ))}
        </div>
      </section>
      )}
    </PageP>
  );
}

window.PageServicesIndex = PageServicesIndex;
window.PageServiceDetail = PageServiceDetail;
